Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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 += 1
1. Eva
2. Anna
3. Max

Python 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 Max

The 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. Max

The 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 points

Instructions

  1. 1

    Write a for loop over enumerate(players) with two loop variables, number and name, that prints both in each iteration. Run the program: the numbers start at 0.

  2. 2

    Now make the numbers start at 1, and print each line as 1. Eva. The output should be 1. Eva, 2. Anna, 3. Max and 4. Tom. Keep the line with the list: the exercise also tries other players.

Back

6/11

  1. 1. Tuples
  2. 2. Unpacking
  3. 3. Quiz: Unpacking
  4. 4. Returning Several Values
  5. 5. A List of Tuples
  6. 6. Numbering with enumerate()
  7. 7. Sets
  8. 8. Adding to a Set
  9. 9. Comparing Sets
  10. 10. Quiz: Sets
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.