Introduction
There are several ways to merge or combine two lists depending on what you want to do.
Using + to concatenate two lists
Creates a new list with elements from both lists:
1 2 3 4 5 | list1 = [1, 2, 3] list2 = [4, 5, 6] merged = list1 + list2 print(merged) # [1, 2, 3, 4, 5, 6] |
Using .extend()
Modifies the first list in place:
1 2 3 4 5 | list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) print(list1) # [1, 2, 3, 4, 5, 6] |
Using unpacking (*)
Simple and very Pythonic:
1 | merged = [*list1, *list2] |
Using itertools.chain
Efficient for large lists:
1 2 3 | from itertools import chain merged = list(chain(list1, list2)) |
Combining two lists using zip
If the goal is not to merge, but to iterate over two lists in parallel, use zip.
Example:
1 2 3 4 5 | l1 = ['a', 'b', 'c'] l2 = [1, 2, 3] for x, y in zip(l1, l2): print(x, y) |
Output:
1 2 3 | a 1 b 2 c 3 |
Note:
zip doesn’t merge the lists into one long list — it pairs their elements:
1 2 | list(zip(l1, l2)) # [('a', 1), ('b', 2), ('c', 3)] |
References
| Links | Site |
|---|---|
| https://docs.python.org/3/tutorial/datastructures.html#more-on-lists | Python Docs — Lists |
| https://docs.python.org/3/library/stdtypes.html#typesseq | Python Docs — Sequence Types (+, unpacking) |
| https://docs.python.org/3/library/itertools.html#itertools.chain | Python Docs — itertools.chain |
| https://docs.python.org/3/library/functions.html#zip | Python Docs — zip |
| https://docs.python.org/3/reference/expressions.html#expression-lists | Python Docs — Unpacking (* operator) |
