This article shows different ways to concatenate two lists or other iterables in Python.
a + b
The simplest way is by just using the + operator to combine two lists:
a = [1, 2] b = [3, 4] c = a + b # [1, 2, 3, 4]
Another alternative has been introduced in Python 3.5 via the acceptance of PEP 448.
This PEP is titled Additional Unpacking Generalizations and is a more general way to unpack and combine items.
While the + operator only works with two lists, this unpacking technique can be used for other iterables (e.g. tuples or sets), too.
c = [*a, *b] # [1, 2, 3, 4]
a = [1, 2] b = (3, 4) # c = a + b # TypeError: can only concatenate list (not "tuple") to list c = [*a, *b] # [1, 2, 3, 4]
Careful: Only creates a shallow copy!
Be careful! Both mentioned methods above create only a shallow copy!
This means the copy is one level deep. Modifying on level 1 does not affect the other list. But with nested objects, modifying on level 2 or deeper does affect the other!
In this example we have a nested list. After creating a new list c, we modify an inner item of a. Notice that c now has the same modification, too!
To learn more about this, visit my blog post about shallow vs deep copying.
# nested lists a = [[1, 2], [3, 4]] b = [[5, 6], [7, 8]] c = a + b print(c) # [[1, 2], [3, 4], [5, 6], [7, 8]] a = 99 print(c) # [[99, 2], [3, 4], [5, 6], [7, 8]]
In-place updates with
To update an existing list in-place, and add the items of another list, you can use
list.extend(iterable). This also works with any type of iterable.
a = [1, 2] b = [3, 4] # also works with other iterables a.extend(b) # a = [1, 2, 3, 4]