How to Iterate Two Lists Simultaneously in Python
You can iterate two lists simultaneously in Python using the
zip() function, which pairs elements from each list together. Use a for loop with zip(list1, list2) to access elements from both lists in each iteration.Syntax
The basic syntax to iterate two lists simultaneously uses the zip() function inside a for loop.
zip(list1, list2): Combines elements fromlist1andlist2into pairs.for a, b in zip(list1, list2):loops over these pairs, assigning elements toaandb.
python
for a, b in zip(list1, list2): # Use a and b here
Example
This example shows how to print elements from two lists side by side using zip().
python
fruits = ['apple', 'banana', 'cherry'] colors = ['red', 'yellow', 'dark red'] for fruit, color in zip(fruits, colors): print(f"The {fruit} is {color}.")
Output
The apple is red.
The banana is yellow.
The cherry is dark red.
Common Pitfalls
One common mistake is assuming zip() works if lists have different lengths. zip() stops at the shortest list, so some elements may be skipped.
To avoid this, use itertools.zip_longest() if you want to include all elements, filling missing values with None or a specified value.
python
from itertools import zip_longest list1 = [1, 2, 3] list2 = ['a', 'b'] # Using zip stops at shortest list for x, y in zip(list1, list2): print(x, y) print('Using zip_longest:') # Using zip_longest includes all elements for x, y in zip_longest(list1, list2): print(x, y)
Output
1 a
2 b
Using zip_longest:
1 a
2 b
3 None
Quick Reference
| Function | Description | Stops at Shortest List? |
|---|---|---|
| zip(list1, list2) | Pairs elements from both lists | Yes |
| itertools.zip_longest(list1, list2) | Pairs elements, fills missing with None | No |
Key Takeaways
Use
zip() to iterate two lists together easily and cleanly.zip() stops at the shortest list, so some elements may be skipped if lists differ in length.Use
itertools.zip_longest() to include all elements when lists have different lengths.Unpack pairs in the
for loop to access elements from both lists simultaneously.