6

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]
3
  • I'm pretty sure that line one and three of both blocks of code are not valid python, unless you defined example to be a list etc with at least 123 elements. Commented Dec 17, 2015 at 14:26
  • 1
    Hint: What does example[4:0] return? What about example[4:1]? And example[4:5]? Try to understand how the slicing works first, then you can deduce why your assignments do the same thing. Commented Dec 17, 2015 at 15:10
  • Thanks guys...finally understood the concept of slicing Commented Dec 20, 2015 at 15:26

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@kanishka Does this answer your question?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.