Start learning free

LESSON 271 OF 673 · TUPLES, SORTING & BUILT-INS

Enumerate and Zip in Python

Lesson

TL ; DR:

enumerate counts the items while you loop. zip walks two lists side by side.


fruits = ["apple", "kiwi", "plum"]
prices = [3, 1, 2]

for number, fruit in enumerate(fruits, start=1):
    print(number, fruit)     # 1 apple, then 2 kiwi, then 3 plum

for fruit, price in zip(fruits, prices):
    print(fruit, price)      # apple 3, then kiwi 1, then plum 2


Full lesson:

You have looped over indexes with range(len(meals)). Then meals[i] gave the item. Python has a shorter way to get both.

enumerate(lst) gives each item of lst together with a count. The loop unpacks each pair into two names, as you did with tuples.

for i, meal in enumerate(meals):
    print(i, meal)

The count starts at 0. To start at 1, write enumerate(meals, start=1). People read numbered lists from 1.

zip(a, b) walks two lists side by side. It pairs the first item of a with the first item of b. Then it pairs the second items, and so on. Each pair is a tuple.

for fruit, price in zip(fruits, prices):
    print(fruit, price)

zip stops at the end of the shorter list. The extra items are skipped, with no error.

The two work together. enumerate(zip(fruits, prices), start=1) gives a count and a pair each time. Put parentheses around the pair's two names.

for number, (fruit, price) in enumerate(zip(fruits, prices), start=1):
    print(f"{number}. {fruit} costs {price}")

Without the parentheses, Python stops with a ValueError. Each item has two parts, not three.


Your task

A quiz show keeps its players in the list players. Their points are in scores, in the same order.

First, print the players as a numbered list from 1, like 1. Ana. Use enumerate.

Then print each player with their points, like Ana has 12 points. Use zip.

Expected output:

1. Ana
2. Ben
3. Cleo
Ana has 12 points
Ben has 9 points
Cleo has 15 points
STEP 1 OF 4
    Ctrl + Enter to check