Python zip(): Loop Over Lists Together
Python's zip() pairs items by position, so you can loop over two lists together.
Loop over two lists
Use two loop variables to unpack each pair.
names = ["Ada", "Sam"]
scores = [8, 6]
for name, score in zip(names, scores):
print(name, score)
This prints Ada 8, then Sam 6.
Handle lists with different lengths
By default, zip() stops when the shortest input runs out.
names = ["Ada", "Sam", "Lee"]
scores = [8, 6]
print(list(zip(names, scores)))
There is no pair for "Lee". Use strict=True when lengths must match.
try:
pairs = list(zip(["Ada", "Sam"], [8], strict=True))
except ValueError:
print("Lists must have the same length")
The length check happens as Python consumes the pairs.
Save the pairs
zip() returns an iterator. Convert it to a list to keep the pairs.
pairs = zip(["Ada", "Sam"], [8, 6])
print(list(pairs))
print(list(pairs))
The second list is empty because the iterator has been used up.
See also: Unpacking, Dictionary comprehension.
Your turn
Loop over names and scores together. Print each name and score.
names = ["Mia", "Leo"]
scores = [9, 7]
# add two lines: loop with zip(), then print the name and score
Expected output
Mia 9
Leo 7