+ 4

Python indexing problem

I don't understand how the following code works, could someone explain how it is assigning elements to the list? lst = [1,2,3,4,5] for i in range(1,6): lst[i:i] = [i] print(lst) https://code.sololearn.com/c3tdEklK3II1

29th Apr 2022, 6:06 PM
Edward Finkelstein
Edward Finkelstein - avatar
6 Respostas
+ 6
Edward Finkelstein , what we have here is a slice on the left side of the expression, this is called slice assignment. just have a look at this line: lst[i:i] = [i] it means that the value of 'i' that is coming from the range object will be inserted at the lst[i:i] position. existing values are not overwritten but they will be moved to the right. for this case you can think about list.insert(). both codes give the same result lst = [1,2,3,4,5] for i in range(1,6): lst[i:i] = [i] print(lst) lst = [1,2,3,4,5] for i in range(1,6): lst.insert(i,i) print(lst) for more information have a look here: https://prosperocoder.com/posts/JUMP_LINK__&&__python__&&__JUMP_LINK/slice-assignment-in-python/ >>> watch also the video on this webpage, it demonstrates the use with some samples.
29th Apr 2022, 6:43 PM
Lothar
Lothar - avatar
+ 7
[i:i] is an empty list . Read it as the list between lst[i] and lst[i+1] Yeah... there is..... nothing. This nothing will be replaced by a list [i].
29th Apr 2022, 7:06 PM
Oma Falk
Oma Falk - avatar
+ 3
It appears to be slicing by the numbers in the list, sequentially... And placing a sequential number in while pushing the rest back. The initial element of a list is list_name[0] So the 1 is untouched... But a 1 is placed afterward... After the first slice. Then slice at list[2] drop in the 2... Then slice at list[3] drop in 3... As it iterates. 1, (1, 2, 3, 4, 5), 2, 3, 4, 5
29th Apr 2022, 6:48 PM
Iain Ozbolt
Iain Ozbolt - avatar
+ 2
Hi, This code shows how to populate the list wih whatever values. I hope it helps lst = [1,2,3,4,5] for i in range(5): lst[i] = i+5 print(lst)
1st May 2022, 8:53 AM
Khalid Alharthi
Khalid Alharthi - avatar
+ 2
For slicing, lst = [1,2,3,4,5] for i in range(1,5): lst[i:i+4] = [i+1] print(lst)
1st May 2022, 8:58 AM
Khalid Alharthi
Khalid Alharthi - avatar