Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing of lists in Python

I am new to Python, could someone please tell me the difference between the output of these two blocks of code:

1.

>> example = [1, 32, 1, 2, 34]
>> example[4:0] = [122]
>> example
[1, 32, 1, 2, 122, 34]

2.

>> example = [1, 32, 1, 2, 34]
>> example[4:1] = [122] 
>> example
[1, 32, 1, 2, 122, 34]
like image 834
kanishka Avatar asked Dec 17 '15 14:12

kanishka


2 Answers

Your slicing gives an empty list at index 4 because the upper bound is less than the lower bound:

>>> example[4:0]
[]

>>> example[4:1]
[]

This empty list is replaced by your list [122]. The effect is the same as doing:

 >>> example.insert(4, 122)

Just remember that empty lists and lists with one element are nothing special, even though the effects they have when you use them are not that obvious in the beginning. The Python tutorial has more details.

like image 170
Mike Müller Avatar answered Oct 16 '22 08:10

Mike Müller


There's nothing wrong here. The output is the same because the only line that is different in the two code snipets is

example[4:0] = [122]

and

example[4:1] = [122]

They both will add and assign the value 122 (I'm assuming list of size one == value here) to the element after that at index 4. since the number in the upper boundary of the slice is less than four in both cases, they have no effect.

like image 40
Elvis Teixeira Avatar answered Oct 16 '22 10:10

Elvis Teixeira