Tip: Loop over multiple Lists with zip

Patrick Loeber

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 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 *

* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses