Skip to content

Tip - How to loop over multiple Lists in Python with the zip function

Learn how to loop over multiple Lists in Python with the zip function.


Don't use a for loop like this for multiple Lists in Python:

a = [1, 2, 3]
b = ["one", "two", "three"]

# ❌ Don't
for i in range(len(a)):
    print(a[i], b[i])

Instead use the handy zip() function:

# ✅ Do
for val1, val2 in zip(a, b):
    print(val1, val2)

zip function in Python

  • zip(*iterables, strict=False)

zip Iterates over several iterables in parallel, producing tuples with an item from each one. If one iterable is shorter than the other, it will simply stop when the last element of the shortest iterable is reached, cutting off the result to the length of the shortest iterable:

a = [1, 2, 3, 4]
b = ["one", "two", "three"]

for val1, val2 in zip(a, b):
    print(val1, val2)
1 one
2 two
3 three

zip with strict argument

Since Python 3.10, the strict argument can be used and set to True in cases where the iterables are assumed to be of equal length. It raises a ValueError if this is not the case:

for val1, val2 in zip(('a', 'b', 'c'), (1, 2, 3, 4), strict=True):
    print(val1, val2)

# Traceback (most recent call last):
#  ...
# ValueError: zip() argument 2 is longer than argument 1

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*


Python Problem-Solving Bootcamp

🚀 Solve 42 programming puzzles over the course of 21 days: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏