Reputation: 6260
I don't quite understand whats happening here
a=[1,2,3,4]
b=[5,6,7,8]
a[len(a):] = b
seems to be an equivalent of a.extend(b)
.
when I say a[(len(a):]
don't I mean a[4:<end of list a>] = b
which is
`nothing in a = b which is
[]
Why am I getting [1,2,3,4,5,6,7,8]
as the result?
Upvotes: 1
Views: 1319
Reputation: 137398
The slice notation is [start : stop]
. Assignment to a list slice like [start:]
causes it to insert the right-hand side sequence at index start
. But because there is no stop
part of the slice, it will always add the entire sequence (without upper bound).
In your case, you are inserting at index 4, which doesn't exist yet, so it inserts it at the end of the original sequence.
Upvotes: 1
Reputation: 798486
Slice assignment can be used to insert one sequence within another (mutable).
>>> a = [1, 2, 3]
>>> a[1:1] = [4, 5]
>>> a
[1, 4, 5, 2, 3]
Your example is simply an instance of inserting at the end.
Upvotes: 10