Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list extend functionality using slices

Tags:

python

slice

I'm teaching myself Python ahead of starting a new job. Its a Django job, so I have to stick to 2.7. As such, I'm reading Beginning Python by Hetland and don't understand his example of using slices to replicate list.extend() functionality.

First, he shows the extend method by

a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)

produces [1, 2, 3, 4, 5, 6]

Next, he demonstrates extend by slicing via

a = [1, 2, 3]
b = [4, 5, 6]
a[len(a):] = b

which produces the exact same output as the first example.

How does this work? A has a length of 3, and the terminating slice index point is empty, signifying that it runs to the end of the list. How do the b values get added to a?

like image 966
Jason Avatar asked Feb 05 '26 08:02

Jason


1 Answers

Python's slice-assignment syntax means "make this slice equal to this value, expanding or shrinking the list if necessary". To fully understand it you may want to try out some other slice values:

a = [1, 2, 3]
b = [4, 5, 6]

First, lets replace part of A with B:

a[1:2] = b
print(a) # prints [1, 4, 5, 6, 3]

Instead of replacing some values, you can add them by assigning to a zero-length slice:

a[1:1] = b
print(a) # prints [1, 4, 5, 6, 2, 3]

Any slice that is "out of bounds" instead simply addresses an empty area at one end of the list or the other (too large positive numbers will address the point just off the end while too large negative numbers will address the point just before the start):

a[200:300] = b
print(a) # prints [1, 2, 3, 4, 5, 6]

Your example code simply uses the most "accurate" out of bounds slice at the end of the list. I don't think that is code you'd use deliberately for extending, but it might be useful as an edge case that you don't need to handle with special logic.

like image 82
Blckknght Avatar answered Feb 06 '26 22:02

Blckknght