Sign in to change your settings
Sign in to your Python Morsels account to save your screencast settings.
Don't have an account yet? Sign up here.
Let's talk about the list extend method.
Appending a list to a list
Have you ever needed to append many items to a list at the same time?
Here, we have two lists:
>>> numbers = [2, 1, 3]
>>> more_numbers = [4, 7, 11]
If we wanted to add all the items from the second list to the first one, we could try to call the append method on the first list, and pass in the second list:
>>> numbers.append(more_numbers)
But this doesn't work the way you might expect. This puts a list within a list:
>>> numbers
[2, 1, 3, [4, 7, 11]]
We wanted a list with 6 elements, but instead we got a list with 4 elements (where the last element just happens to be a list):
>>> len(numbers)
4
We could fix this by using a for loop and then appending each item one-by-one:
>>> numbers = [2, 1, 3]
>>> more_numbers = [4, 7, 11]
>>> for n in more_numbers:
... numbers.append(n)
>>> numbers
[2, 1, 3, 4, 7, 11]
This works. But there's an even easier way to do this.
Extending a list
The list extend method accepts an iterable, loops over the given iterable, and appends each item to the list:
>>> numbers = [2, 1, 3]
>>> more_numbers = [4, 7, 11]
>>> numbers.extend(more_numbers)
>>> numbers
[2, 1, 3, 4, 7, 11]
The extend method is pretty much the same as looping over a list and calling append repeatedly.
Extending any iterable
The list extend method is great for adding all the items from one list to another.
But the extend method doesn't just accept lists.
It accepts any iterable.
So the extend method can accept a tuple or a range object, and it'll work just the same as if we passed in lists:
>>> numbers = [2, 1, 3]
>>> numbers.extend((4, 7, 11))
>>> numbers
[2, 1, 3, 4, 7, 11]
>>> numbers.extend(range(100, 103))
>>> numbers
[2, 1, 3, 4, 7, 11, 100, 101, 102]
In-place list concatenation
The extend method isn't the only way to add a bunch of items to a list.
We can also use Python's += syntax to extend a list:
>>> numbers = [2, 1, 3]
>>> more_numbers = [4, 7, 11]
>>> numbers += more_numbers
>>> numbers
[2, 1, 3, 4, 7, 11]
Assignment with += is often called in-place addition.
It's similar to concatenation, but it modifies the original list, the same way the extend method does.
In fact, just like the extend method, using += on a list will work on any iterable.
>>> numbers = [2, 1, 3]
>>> numbers += (4, 7, 11)
>>> numbers
[2, 1, 3, 4, 7, 11]
>>> numbers += range(100, 103)
>>> numbers
[2, 1, 3, 4, 7, 11, 100, 101, 102]
Whether you use += or extend is up to you.
They both do the same thing.
Use extend or += to add multiple items to a list
The next time you need to add an iterable of items to a list, use the list extend method, or an in-place assignment with +=.
A Python tip every week
Need to fill-in gaps in your Python skills?
Sign up for my Python newsletter where I share one of my favorite Python tips every week.