3

I'm new to python, and while reading about slice notation, I came across the following code snippet. I was able to understand and use it in very simple examples, but I wasn't able to grasp its usage in the following example. Any explanation will really help!

>>> a = [1,2]
>>> a[1:1] = [3,4,5]
>>> print a
[1, 3, 4, 5, 2]

>>> a = [1,2]
>>> a[0:1] = [3,4,5]
>>> print a
[3, 4, 5, 2]

2 Answers 2

6
a[n:m] = b
# is essentially* equivalent to
a = a[:n] + b + a[m:]

and you could read this as "replace a[n:m] with b" (since a = a[:n] + a[n:m] + a[m:]).

*actually slicing mutates the list in-place (that is, id(a) remains unchanged) which will usually be preferable (wheras setting a= creates our new a at a different memory location).

So in your examples:

a = [1,2]
#a[1:1] = [3,4,5]
a = a[:1] + [3,4,5] + a[1:]
#   [1]               [2]
[1, 3, 4, 5, 2]

a = [1,2]
#a[0:1] = [3,4,5]
a = a[:0] + [3,4,5] + a[1:]
#   []                [2]
[3, 4, 5, 2]
Sign up to request clarification or add additional context in comments.

1 Comment

Does this modify the underlying list object directly? If so, your equivalence isn't quite equivalent. Probably worth a note either way. It's a good aide to understanding, anyway.
0

a[1:1] is an empty slice at the position between the first and second elements in the list.
So a[1:1] = [3,4,5] means "insert the elements 3,4,5 after the first element of the list".

a[0:1] is the slice from the first element up to (but excluding) the second element in the list.
So a[0:1] = [3,4,5] means "replace the first element of the list with the elements 3,4,5".

Perhaps this visualization helps:

| h | e | l | l | o |    <-- string "hello"
0   1   2   3   4   5    <-- slice positions
^---^                    <-- slice [0:1]: "h"
    ^                    <-- slice [1:1]: ""

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.