enumerate() in Python: the item and its index at once
Sometimes you need both the item and its position in the loop. enumerate() hands you both — no clumsy counter to maintain by hand.
The big idea
enumerate(seq) yields (index, item) pairs, so a loop gets each item together with its position.
See it in code
enumerate(seq) yields (index, item) pairs. Unpack them into i and the item, and the loop gets each value together with its position:
names = ["Blaze", "Nova", "Rex"]
for i, name in enumerate(names):
print(i, name)0 Blaze 1 Nova 2 Rex
No counter to maintain — enumerate handed back 0, 1, 2 alongside each name, in one clean step.
The index is a number, so you can compute with it. Here we turn each enemy's place in line into an evenly spaced x-position:
wave = ["enemy", "enemy", "enemy"]
for i, e in enumerate(wave):
print(f"enemy {i} -> x={55 + i * 74}")enemy 0 -> x=55 enemy 1 -> x=129 enemy 2 -> x=203
55 + i * 74 maps each index to a spot. Now let's run that on real Enemy objects and actually place them.
We have a list of enemies stacked at the same spot and want to spread them out. enumerate(wave) gives us i alongside each enemy, so we set each one's x from its place in line — the exact formula from the warm-up:
from game import Stage, Enemy
screen = Stage.create()
Stage.clear(screen)
wave = [Enemy(0, 90) for _ in range(6)]
for i, enemy in enumerate(wave):
enemy.x = 55 + i * 74
print(f"enemy {i} -> x={enemy.x}")
enemy.draw(screen)enemy 0 -> x=55 enemy 1 -> x=129 enemy 2 -> x=203 enemy 3 -> x=277 enemy 4 -> x=351 enemy 5 -> x=425

enumerate unpacked each pair into i and enemy in one clean step. It starts at 0 by default, but enumerate(wave, start=1) would number them from 1 — handy for human-facing lists.
Any time you loop and need positions, enumerate beats a manual counter: numbering menu options, labeling rows of data, finding the index of a match, laying out a grid. It's clearer than tracking i += 1 yourself, and impossible to forget to increment.
Try it yourself
Add start=1 and watch the printed numbers shift. Then use the index to alternate color or spacing — if i % 2 == 0 for every other enemy — a common 'stripe' pattern.
The common mistake
Falling back to for i in range(len(wave)) and indexing wave[i] everywhere. It works, but it's noisier and error-prone. When you need both the index and the item, enumerate is the idiomatic, less-buggy choice.
What it unlocks
enumerate sharpens for loops over lists, and pairs naturally with list indexing.