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
names = ["Ada", "Linus", "Grace"] scores = [91, 78, 85] for rank, (name, score) in enumerate(zip(names, scores), start=1): print(f"{rank}. {name}: {score}")
1. Ada: 91 2. Linus: 78 3. Grace: 85
How it works
zip(names, scores)gives the pairs("Ada", 91),("Linus", 78)and("Grace", 85).enumerate(..., start=1)adds a number to each pair, starting at 1 (the default is 0). Each item is now(1, ("Ada", 91)).- The loop variables
rank, (name, score)copy that shape. The brackets around(name, score)unpack the inner pair into two names.
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:
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)
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.