Iterating with enumerate

A for loop can go through a list one item at a time. If you also need each item's position, use enumerate.

players = ["Mira", "Noah", "Zoe"]
scores = [7, 9, 6]
total = 0

for number, player in enumerate(players, 1):
    print(f"{number}. {player}")

for score in scores:
    total += score

print("total:", total)

Output:

1. Mira
2. Noah
3. Zoe
total: 22

On each step, enumerate gives you a pair: a number and an item. The loop has two names, number, player, so the number goes into number and the item goes into player. This is called unpacking. You will learn more about it in the tuples lesson later in this section.

The second argument to enumerate, 1, tells it to start counting at 1. This only changes the numbers you print. The list's indexes still start at 0.

Do not add or remove items in a list while you loop over that same list. The loop keeps track of its place by index. When you remove an item, the next item moves back one place, into a spot the loop has already passed:

numbers = [1, 2, 2, 3]
for number in numbers:
    if number == 2:
        numbers.remove(number)
print(numbers)

Output:

[1, 2, 3]

One 2 is still in the list, because the loop skipped it. Instead, build a new list, or make the changes after the loop ends.

In the exercise, print a numbered menu and add up its prices.