Python enumerate(): Loop with Index and Value
enumerate() gives each item of a list together with its position, so a for loop gets the index and the value at once.
Read For loops and Unpacking first.
Loop with index and value
Put two names after for. The first gets the index, the second gets the
item.
players = ["Ada", "Ben", "Cy"]
for i, name in enumerate(players):
print(i, name)
The index starts at 0, like list positions. Each turn, enumerate() hands
over a pair such as (0, "Ada"), and i, name unpacks it.
Start counting from 1
Pass start=1 to number the items the way people count.
podium = ["Ada", "Ben", "Cy"]
for place, name in enumerate(podium, start=1):
print(f"{place}. {name}")
start changes only the numbers. The loop still begins at the first item.
Replace range(len(...)) with enumerate()
Without enumerate(), you loop over positions and index the list yourself.
It works, but it is harder to read.
scores = [12, 7, 15]
for i in range(len(scores)):
print(i, scores[i])
for i, score in enumerate(scores):
print(i, score)
Both loops print the same three lines. The second one names the item
directly, so there is no scores[i] to get wrong.
Find the position of a match
Use the index when you need to report or change where something is.
rolls = [3, 6, 2, 6]
for i, roll in enumerate(rolls):
if roll == 6:
rolls[i] = 0
print("Six at position", i)
print(rolls)
rolls[i] = 0 writes back to the list at that position. Changing roll
alone would not change the list.
Note: enumerate() works on anything you can loop over, not just lists.
enumerate("hi") gives (0, "h"), then (1, "i").
See also: The range() function, Lists.
Your turn
enumerate() works on a string too. Print the index of every "X" in
board, one per line.
board = "X.OX.X"
# add three lines: loop over enumerate(board); when the cell is "X", print its index
Expected output
0
3
5