How to Zip Two Lists in Python: Simple Guide
You can combine two lists element-wise in Python using the
zip() function. It pairs elements from each list into tuples, stopping at the shortest list length.Syntax
The zip() function takes two or more iterables (like lists) and returns an iterator of tuples. Each tuple contains one element from each iterable at the same position.
Basic syntax:
zip(list1, list2): Combines elements fromlist1andlist2.- The result is an iterator, so you often convert it to a list with
list(zip(...))to see all pairs.
python
zipped = zip(list1, list2) result = list(zipped)
Example
This example shows how to zip two lists of names and ages into pairs.
python
names = ['Alice', 'Bob', 'Charlie'] ages = [25, 30, 35] zipped_lists = list(zip(names, ages)) print(zipped_lists)
Output
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]
Common Pitfalls
One common mistake is expecting zip() to handle lists of different lengths by filling missing values. Instead, zip() stops at the shortest list length.
Also, remember that zip() returns an iterator, so you need to convert it to a list or loop over it to see the pairs.
python
list1 = [1, 2, 3] list2 = ['a', 'b'] # Wrong: expecting all elements paired print(list(zip(list1, list2))) # Output: [(1, 'a'), (2, 'b')] - stops at shortest list # Right: use itertools.zip_longest to fill missing values from itertools import zip_longest print(list(zip_longest(list1, list2, fillvalue='missing')))
Output
[(1, 'a'), (2, 'b')]
[(1, 'a'), (2, 'b'), (3, 'missing')]
Quick Reference
Remember these points when using zip():
- Pairs elements by position from each list.
- Stops at the shortest list length.
- Returns an iterator, convert to list to view all pairs.
- Use
itertools.zip_longest()to handle uneven lists.
Key Takeaways
Use
zip() to pair elements from two lists by their positions.zip() stops at the shortest list length, so extra elements are ignored.Convert the
zip() result to a list to see all pairs at once.For lists of different lengths, use
itertools.zip_longest() to fill missing values.Remember
zip() returns an iterator, not a list.