Hi Pythonistas!
Today I'm sharing one of Python’s most elegant and useful features — but surprisingly underused: the zip() function.
Whenever I need to iterate over multiple sequences together, zip() saves the day — and makes the code cleaner, safer, and more Pythonic.
The Problem: Parallel Loops Without zip()
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for i in range(len(names)):
print(f"{names[i]} scored {scores[i]}")
This works, but:
- It’s verbose
- It assumes both lists are the same length
- You risk IndexError if they aren’t
✅ The Pythonic Way: Use zip()
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
This is more:
- Elegant
- Safe
- Readable
Bonus: Use zip() with enumerate() for Index Tracking
for i, (name, score) in enumerate(zip(names, scores), start=1):
print(f"{i}. {name} scored {score}")
Be Careful
zip() stops at the shortest input:
names = ["Alice", "Bob"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
Output:
Alice scored 85
Bob scored 92
The third score (78) is silently ignored!
If You Need Full Length + Fill Missing Use itertools.zip_longest
from itertools import zip_longest
for name, score in zip_longest(names, scores, fillvalue="N/A"):
print(f"{name} scored {score}")
Output
Alice scored 85
Bob scored 92
N/A scored 78
TL;DR
- Use zip() for looping through multiple lists in parallel
- Don’t use range(len(...)) unless you absolutely have to
- For unequal lengths, go with itertools.zip_longest()