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
Loop over related lists together
zipNeed to loop over two lists at the same time?
Use zip() to pair related values together.
zipYou 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
zipzip() 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.
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)
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.
enumerateUse 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
Now you can use zip() to loop over related lists together.
Follow me for more tips.
Shep Bryan IV