1

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?

2 Answers 2

10

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.

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

Comments

1

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.

Python Docs 3.1.4 Lists

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.