CollectionsChapter 33 of 114
Join Lists
Put two lists together, and turn a list into a string.
Adding two lists
+ makes a new list from two:
first = [1, 2]
second = [3, 4]
print(first + second)
print(first)Output
[1, 2, 3, 4] [1, 2]
Neither original changed.
Extending in place
extend() and += add the items to the list you already have:
first = [1, 2]
first.extend([3, 4])
print(first)
other = [1]
other += [2, 3]
print(other)Output
[1, 2, 3, 4] [1, 2, 3]
Use + when you want a new list, extend() when you want to grow this one.
Unpacking into a new list
The star spreads a list into a new one, and takes any number of sources:
first = [1, 2]
second = [3]
third = [4, 5]
print([*first, *second, *third])
print([0, *first, 99])Output
[1, 2, 3, 4, 5] [0, 1, 2, 99]
This is often the clearest option, because it puts everything in one expression without touching the originals.
Flattening a list of lists
groups = [[1, 2], [3], [4, 5]]
flat = [item for group in groups for item in group]
print(flat)Output
[1, 2, 3, 4, 5]
itertools.chain does the same without building the intermediate list:
from itertools import chain
groups = [[1, 2], [3], [4, 5]]
print(list(chain.from_iterable(groups)))Output
[1, 2, 3, 4, 5]
Interleaving with zip
names = ["Ada", "Grace"]
years = [1815, 1906]
print(list(zip(names, years)))Output
[('Ada', 1815), ('Grace', 1906)]Turning a list into a string
This is str.join(), and the separator is the string you call it on:
names = ["Ada", "Grace", "Katherine"]
print(", ".join(names))
print("".join(["a", "b", "c"]))Output
Ada, Grace, Katherine abc
numbers = [1, 2, 3]
print(", ".join(str(n) for n in numbers))Output
1, 2, 3
Repeating a list
* repeats, the same as with strings:
print([0] * 5)Output
[0, 0, 0, 0, 0]
grid = [[0] * 2] * 3
grid[0][0] = 99
print(grid)Output
[[99, 0], [99, 0], [99, 0]]
Build each row separately instead:
grid = [[0] * 2 for _ in range(3)]
grid[0][0] = 99
print(grid)Output
[[99, 0], [0, 0], [0, 0]]
Test yourself
2 questionsWhat does ", ".join([1, 2, 3]) do?
Show the answer
Raises TypeError — join needs every item to be a string already. Convert first with str().
Why is [[0] 2] 3 dangerous?
Show the answer
All three rows are the same list, so changing one changes all — Repeating copies the reference, not the list. Build each row separately in a comprehension.
List Methods
The full set of list methods, and which return a value rather than None.