Raj
Raj

Reputation: 4462

Slice notation in python - need clarification on a code snippet

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]

Upvotes: 3

Views: 153

Answers (2)

Andy Hayden
Andy Hayden

Reputation: 375785

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]

Upvotes: 6

Tim Pietzcker
Tim Pietzcker

Reputation: 336438

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]: ""

Upvotes: 0

Related Questions