Show the zip approach and the nested-loop approach for pairing two sequences, and compare them.
zip is the built-in way to iterate over several sequences in lockstep. It returns an iterator of tuples, and tuple unpacking gives you one variable per sequence.
names = ["ada", "grace", "alan"]
scores = [99, 87, 91]
# zip - the idiomatic form
for name, score in zip(names, scores):
print(name, score)
# The explicit nested loop
for index in range(len(names)):
print(names[index], scores[index])
# zip plus enumerate, when you need the index too
for index, (name, score) in enumerate(zip(names, scores)):
print(index, name, score)All three print the same three pairs. The zip version is the one to write. The nested loop repeats the indexing on every line, has to assume the two lists are the same length, and gets noisier the more sequences you add. The third version is worth knowing because combining enumerate with zip is the standard way to get an index and a pair of values at the same time.
The important behaviour to know is that zip stops at the shortest sequence. If scores were shorter than names, the extra names would be silently dropped and you would never know. That is often the behaviour you want when pairing two files of equal length, but it is a genuine trap when the lengths are supposed to match and do not.
Two more details. zip is lazy, so it does not build a list of pairs in memory unless you wrap it in list(). And it works with any number of sequences, not just two, so a three-way zip is simply zip(a, b, c).