When you are working with multiple lists, you may want to iterate through multiple lists in parallel to process paired elements: (name, age), (x, y) coordinates, etc.
Here are different ways to iterate:
Method 1: Using zip()
The most Pythonic way to iterate over two lists in parallel is to use the zip() method. The zip() method returns an iterator that is more memory efficient.
stocks = ['Alphabet', 'Apple', 'Nvidia']
prices = [315, 286, 181]
for stock, price in zip(stocks, prices):
print(f"{stock} - {price}")
# Output:
# Alphabet - 315
# Apple - 286
# Nvidia - 181
In this code, we are iterating over the stocks and prices list and printing a pair of stock-price one-by-one using a for loop and the zip() function.
Unequal lengths
What if one list has a length of 2 and the other has a length of 3? How will it iterate then? In that case, the zip() function stops at the shortest list and truncates the remaining elements.
stocks = ['Alphabet', 'Apple', 'Nvidia'] # Length is 3
prices = [315, 286] # Length is 2
for stock, price in zip(stocks, prices):
print(f"{stock} - {price}")
# Output:
# Alphabet - 315
# Apple - 286
Method 2: Using itertools.longest()
What if you still want to iterate over the complete two lists with unequal lengths? In that case, you should use the itertools.zip_longest() method. It replaces None with empty values.
import itertools
stocks = ['Alphabet', 'Apple', 'Nvidia'] # Length is 3
prices = [315, 286] # Length is 2
for stock, price in itertools.zip_longest(stocks, prices, fillvalue=None):
print(f"{stock} - {price}")
# Output:
# Alphabet - 315
# Apple - 286
# Nvidia - None
In this code, we explicitly set empty values to None by passing the fillValue=None argument to itertools.zip_longest() method.
Method 3: List Comprehension with zip()
If you want to create a transformed list while iterating over two lists simultaneously in Python, use the list comprehension with the zip() function.
stocks = ['Alphabet', 'Apple', 'Nvidia'] # Length is 3
prices = [315, 286, 185] # Length is 3
results = [f"{n}: {s}" for n, s in zip(stocks, prices)]
print(results)
# Output:
# ['Alphabet: 315', 'Apple: 286', 'Nvidia: 185']
That’s all!



