PythonMastery

enumerate and zip together in Python

Loop over two lists side by side with zip(), number the rows with enumerate(), and use both at once. What zip does when the lists have different lengths.

zip() walks through two lists side by side, giving one pair at a time. enumerate() adds a count to each item. Together they print numbered rows from two lists.

The program

python
names = ["Ada", "Linus", "Grace"]
scores = [91, 78, 85]

for rank, (name, score) in enumerate(zip(names, scores), start=1):
    print(f"{rank}. {name}: {score}")
output
1. Ada: 91
2. Linus: 78
3. Grace: 85

How it works

Lists of different lengths

zip() stops at the end of the shortest list, without an error. Extra items in the longer list are ignored. If the lists should always have the same length, strict=True (Python 3.10 and later) raises a ValueError instead:

python
names = ["Ada", "Linus", "Grace", "Alan"]
scores = [91, 78, 85]

for name, score in zip(names, scores):
    print(name, score)

try:
    for name, score in zip(names, scores, strict=True):
        pass
except ValueError as error:
    print("Error:", error)
output
Ada 91
Linus 78
Grace 85
Error: zip() argument 2 is shorter than argument 1

Alan has no score, so the first loop leaves him out without any warning. With strict=True, the mistake is reported.

The enumerate and zip tip has more examples.

Related programs: Convert two lists into a dictionary.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Lists & Sequences

A longer explanation: Loop with enumerate and zip, not range(len())