Legends ofPythos
Claim your name
Pythonic Python

enumerate and zip

Lesson 1 of 12

Watch the lesson5:49 ยท with Sigrid
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}')
Prints each task with its index
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}')
Starts numbering from 1
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}')
Pairs names with their scores
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.

Your turn

0 of 3 solved

Exercise 1

+30 XP
Write a function numbered(items) that returns a list of strings where each item is prefixed with its position number, starting from 1. Use enumerate with the start argument. For example: ['a', 'b'] becomes ['1: a', '2: b'].
def numbered(items):
    pass

Run your code to check it against the tests.

Exercise 2

+30 XP
Write a function pair(names, scores) that zips two lists together and returns a list of tuples. For example: (['A', 'B'], [90, 85]) becomes [('A', 90), ('B', 85)]. If one list is shorter, stop at the shorter one. zip hands out its pairs as tuples, one at a time: put list() round it to get them all in one list.
def pair(names, scores):
    pass

Run your code to check it against the tests.

Exercise 3

+30 XP
Write a function leaderboard(names, scores) that pairs each name with its score using zip, numbers the pairs from 1 using enumerate, and returns a list of strings in the form '1. Ada - 92'. If one list is shorter, stop at the shorter one. Each pair from zip is a tuple, such as ('Ada', 92), and enumerate can number those pairs, just as it numbers list items.

Example: (['Ada', 'Grace'], [92, 85]) returns ['1. Ada - 92', '2. Grace - 85'].
def leaderboard(names, scores):
    pass

Run your code to check it against the tests.