Sometimes you need each item in a list and its position too: for example, to number the lines of a report, or to match names with their scores. One way is to loop over the positions, with
for i in range(len(my_list)):. len(my_list) is how many items there are, so range(len(my_list)) counts 0, 1, 2 and so on, and my_list[i] looks up each item. That works, but it's noisy and easy to get wrong. Python has two tools that do the job for you: enumerate and zip.enumerate()
tasks = ['write', 'test', 'deploy']
for i, t in enumerate(tasks):
print(f'{i}: {t}')enumerate wraps your list into pairs of (index, value). You unpack them directly in the loop header. This is cleaner than manual counting because Python handles the indexing for you.tasks = ['write', 'test', 'deploy']
for i, t in enumerate(tasks, start=1):
print(f'{i}. {t}')The
start argument lets you change where counting begins. This is useful for human-facing output, like numbered lists in a UI or report.zip()
names = ['Ada', 'Grace']
scores = [92, 85]
for n, s in zip(names, scores):
print(f'{n} scored {s}')zip joins two lists item by item: first with first, second with second. Each pair comes out as a tuple, such as ('Ada', 92). To keep all the pairs, put list() round it: list(zip(names, scores)) gives [('Ada', 92), ('Grace', 85)].zip stops when the shorter list runs out, and leaves out any extra items in the longer one. So zip itself won't read past the end of a list, the slip that stops a program with an IndexError.You now have the tools to write functions like
numbered(items) using enumerate, or pair(names, scores) using zip. enumerate can number the pairs from zip, too: in for i, p in enumerate(zip(names, scores), start=1):, i is the rank and p is one pair, such as ('Ada', 92). These patterns show up constantly: numbered receipts, paired sensor readings, ranked leaderboards. Your code will be shorter and less error-prone.