list.extend()
Adds every item from another list, tuple, string or other iterable to the end of a list, one by one, in place.
list.extend(iterable)extend() takes a collection and adds each of its items to the end of your list. After a.extend(b), the list a holds its old items followed by all the items of b.
Use it to join lists without making a new one, for example to add the results of each page of data to one big list.
The classic surprise: extend() loops over whatever you give it. A string is a collection of characters, so letters.extend("hi") adds 'h' and 'i' as two items. To add a whole string as one item, use list.append().
Parameters
| Parameter | What it is |
|---|---|
iterablerequired | Any collection you can loop over: a list, tuple, set, string, range, dictionary (adds its keys) or generator. |
Return value
Nothing (None). The list is changed in place.
Examples
1Join two lists
fruit = ["apple", "pear"]
more = ["plum", "kiwi"]
fruit.extend(more)
print(fruit)
print(more)['apple', 'pear', 'plum', 'kiwi'] ['plum', 'kiwi']
Only fruit changes. The list you pass in stays as it was.
2extend() vs append()
a = [1, 2]
a.extend([3, 4])
print(a)
b = [1, 2]
b.append([3, 4])
print(b)[1, 2, 3, 4] [1, 2, [3, 4]]
3Any iterable works
A tuple, a range and a string are all collections, so extend() takes each of their items.
items = [0]
items.extend((1, 2))
items.extend(range(3, 5))
items.extend("ab")
print(items)[0, 1, 2, 3, 4, 'a', 'b']
4Gather results from several pages
pages = [["Lena", "Omar"], ["Yuki"], ["Sam", "Ines"]]
all_users = []
for page in pages:
all_users.extend(page)
print(all_users)
print(len(all_users), "users")['Lena', 'Omar', 'Yuki', 'Sam', 'Ines'] 5 users
Common mistakes
Extending with a string
A string is split into its characters. Wrap it in a list, or use append().
tags = ["python"]
tags.extend("web")
print(tags)
tags = ["python"]
tags.extend(["web"])
print(tags)['python', 'w', 'e', 'b'] ['python', 'web']
Expecting extend() to return the new list
Like every method that changes a list, extend() returns None. If you want a new list and keep both old ones, use a + b.
a = [1, 2]
b = [3]
print(a.extend(b))
print(a)
c = [1, 2] + [3]
print(c)None [1, 2, 3] [1, 2, 3]
Questions people ask
What is the difference between extend() and +?
a.extend(b) changes a. a + b builds a brand-new list and leaves both unchanged. a += b behaves like extend(): it changes a in place.
How do I merge more than two lists?
Call extend() once per list, or write [*a, *b, *c] to build a new list in one line.
Can I extend a list with a dictionary?
Yes, but you get its keys. Use items.extend(d.values()) for the values or items.extend(d.items()) for key-value pairs.