Numbering with enumerate()
To print a numbered list, you could count with a variable of your own:
players = ["Eva", "Anna", "Max"]
number = 1
for name in players:
print(f"{number}. {name}")
number += 11. Eva
2. Anna
3. MaxPython can count for you. The function enumerate() gives the loop a tuple in each iteration: the number of the element, and the element itself. You unpack it into two loop variables:
players = ["Eva", "Anna", "Max"]
for number, name in enumerate(players):
print(number, name)0 Eva
1 Anna
2 MaxThe numbers start at 0: they are the indexes of the elements. A list for people to read should start at 1. You tell enumerate() where to start with start=1, written like end= in print(): the name of the argument, an equals sign and the value:
for number, name in enumerate(players, start=1):
print(f"{number}. {name}")1. Eva
2. Anna
3. MaxThe number always comes first and the element second. for name, number in enumerate(players): runs too, but then name holds the numbers and number the names.
When the elements are tuples themselves, such as results with a name and points, unpack each of them in the body of the loop:
results = [("Eva", 15), ("Anna", 12)]
for place, result in enumerate(results, start=1):
name, points = result
print(f"{place}. {name}: {points} points")1. Eva: 15 points
2. Anna: 12 pointsInstructions
- 1
Write a
forloop overenumerate(players)with two loop variables,numberandname, that prints both in each iteration. Run the program: the numbers start at 0. - 2
Now make the numbers start at 1, and print each line as
1. Eva. The output should be1. Eva,2. Anna,3. Maxand4. Tom. Keep the line with the list: the exercise also tries other players.