enumerate()

Iterate over a sequence together with a running index, without managing a counter variable by hand.

                enumerate(iterable, start=0)
              

Purpose

enumerate(iterable, start=0) returns an iterator of (index, item) pairs — the standard way to get both a position and a value while looping, without a separate counter you increment by hand.

Example

fruits = ["apples", "bananas", "cherries"]

for index, fruit in enumerate(fruits, start=1):
    print(f"{index}. {fruit}")
1. apples
2. bananas
3. cherries

Behavior notes

  • start defaults to 0; pass start=1 (as in the example above) whenever the numbering should read naturally for a person rather than match Python’s own 0-based indexing.
  • enumerate is lazy — it produces pairs one at a time as the loop asks for them, rather than building the whole list of pairs up front.
  • Each pair is a 2-tuple, which is exactly what the for index, item in enumerate(...): unpacking syntax expects.

Common mistakes

  • Writing a manual counter (i = 0, then i += 1 inside the loop) instead of enumerate — it works, but it’s more code, and it’s easy to increment in the wrong place or forget to.
  • Calling list(fruits).index(fruit) inside a loop to recover the current position — that re-searches the whole list on every iteration and gives the wrong answer if a value repeats; enumerate gives the correct position directly, in one pass.

Implementation notes

enumerate’s laziness and pairing behavior are guaranteed by the language — identical across conforming implementations.

Taught in these lessons

Related reference