Python Tip: zip

Loop over related lists together

Learn how to use zip to loop over related lists together without manual indexing.
Author

Shep Bryan IV

Python Tip: zip

Need to loop over two lists at the same time?

Use zip() to pair related values together.

Without zip

You can use indexes to read from two lists, but it makes the loop harder to read.

names = ["Ada", "Grace", "Katherine"]
scores = [98, 95, 99]

for i in range(len(names)):
    print(names[i], scores[i])
Ada 98
Grace 95
Katherine 99

With zip

zip() pairs the first item from each list, then the second, then the third.

names = ["Ada", "Grace", "Katherine"]
scores = [98, 95, 99]

for name, score in zip(names, scores):
    print(name, score)
Ada 98
Grace 95
Katherine 99

Cleaner loop. Same result.

More Than Two Lists

You can zip three or more lists when each item has multiple related values.

names = ["Ada", "Grace", "Katherine"]
scores = [98, 95, 99]
grades = ["A", "A", "A"]

for name, score, grade in zip(names, scores, grades):
    print(f"{name}: {score} ({grade})")
Ada: 98 (A)
Grace: 95 (A)
Katherine: 99 (A)

Watch the Lengths

zip() stops when the shortest list runs out of items.

names = ["Ada", "Grace", "Katherine"]
scores = [98, 95]

for name, score in zip(names, scores):
    print(name, score)
Ada 98
Grace 95

Katherine is skipped because there is no matching score.

Combine with enumerate

Use enumerate() with zip() when you also need a counter.

names = ["Ada", "Grace", "Katherine"]
scores = [98, 95, 99]

for rank, (name, score) in enumerate(zip(names, scores), start=1):
    print(f"{rank}. {name}: {score}")
1. Ada: 98
2. Grace: 95
3. Katherine: 99

Wrap-Up

Now you can use zip() to loop over related lists together.

Follow me for more tips.
Shep Bryan IV