kanishka
kanishka

Reputation: 69

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]

Upvotes: 6

Views: 132

Answers (2)

Mike Müller
Mike Müller

Reputation: 85612

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.

Upvotes: 5

Elvis Teixeira
Elvis Teixeira

Reputation: 614

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.

Upvotes: 1

Related Questions