How to Combine Lists with zip() in Python
Combining multiple lists into a single, cohesive data structure is a frequent task in data processing, whether you are aligning names with scores, coordinates, or dictionary keys with values. Python's built-in zip() function is the most efficient and readable tool for this job.
This guide explores how zip() works, how to handle lists of different lengths, and advanced unpacking techniques.
Understanding zip() Mechanics
The zip() function takes multiple iterables (lists, tuples, etc.) and aggregates them into an iterator of tuples.
- Lazy Evaluation:
zip()returns an iterator, not a list. To see the contents, you must iterate over it or convert it usinglist()ortuple(). - Parallel Iteration: It grabs the first element from every list, then the second, and so on.
Method 1: Creating a List of Tuples
The most common use case is pairing elements from two lists.
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
# ✅ Correct: Combining lists
# Note: Wrap in list() to view the result immediately
combined = list(zip(names, scores))
print(combined)
Output:
[('Alice', 85), ('Bob', 92), ('Charlie', 78)]
Iterating in Parallel
Instead of using indices (e.g., names[i], scores[i]), you can loop through both lists simultaneously.
for name, score in zip(names, scores):
print(f"{name} scored {score}")
Output:
Alice scored 85
Bob scored 92
Charlie scored 78
Method 2: Creating a Dictionary
If you have one list of keys and one list of values, zip() is the fastest way to construct a dictionary.
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']
# ✅ Correct: Convert zipped pairs directly to dict
person_dict = dict(zip(keys, values))
print(person_dict)
Output:
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Method 3: Unzipping (Reversing the Operation)
You can use the unpacking operator * to reverse the zip operation, separating a list of tuples back into independent lists.
coordinates = [(1, 2), (3, 4), (5, 6)]
# ✅ Correct: Unzip using *
x_coords, y_coords = zip(*coordinates)
print(f"X: {x_coords}")
print(f"Y: {y_coords}")
Output:
X: (1, 3, 5)
Y: (2, 4, 6)
Handling Unequal Lengths
By default, zip() stops as soon as the shortest list is exhausted. The remaining items in longer lists are ignored.
list_a = [1, 2, 3]
list_b = ['a', 'b'] # Shorter
print(list(zip(list_a, list_b)))
Output:
[(1, 'a'), (2, 'b')]
Using zip_longest (Padding)
If you want to keep all elements, use itertools.zip_longest. It fills missing values with None (or a custom fillvalue).
from itertools import zip_longest
list_a = [1, 2, 3]
list_b = ['a', 'b']
# ✅ Correct: Keeping all data
padded_zip = list(zip_longest(list_a, list_b, fillvalue="?"))
print(padded_zip)
Output:
[(1, 'a'), (2, 'b'), (3, '?')]
Conclusion
To combine lists in Python:
- Use
zip(a, b)for memory-efficient, parallel iteration. - Use
dict(zip(keys, values))to create dictionaries instantly. - Use
zip(*zipped_list)to transpose or unzip data. - Use
itertools.zip_longestif your lists have different lengths and you cannot afford to lose data.