Skip to content

enumerate()

enumerate(iterable, start=0) wraps any iterable and yields (index, value) pairs as you loop, so you get the position of each item without maintaining a manual counter variable.

fruits = ["apple", "banana", "cherry"]
i = 0
for fruit in fruits:
print(i, fruit)
i += 1
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(i, fruit)
# 0 apple
# 1 banana
# 2 cherry
for i, fruit in enumerate(fruits, start=1): # custom starting index
print(i, fruit)
# 1 apple
# 2 banana
# 3 cherry
print(list(enumerate(fruits)))
# [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
  • No manual counter to forget updating: i += 1 is exactly the kind of off-by-one bug source that enumerate eliminates.
  • Reads as intent: for i, fruit in enumerate(fruits) says β€œindex and value” directly, versus reconstructing that meaning from a separate counter variable.
  • Lazy, like range: enumerate is itself an iterator β€” it doesn’t build a list of all the pairs upfront unless you explicitly convert it with list(...).
  • enumerate works on any iterable, not just lists β€” strings, generators, file objects (line number + line text is a common use: for lineno, line in enumerate(f, start=1)).
  • The start parameter changes the first index emitted, not which items are iterated β€” enumerate(fruits, start=1) still visits all three fruits, just numbered from 1.
  • Common mistake: calling enumerate(fruits.items()) on a dict β€” dicts already yield keys when iterated, so enumerate(d) gives (index, key), not (index, key, value); for indexed key/value pairs you’d need enumerate(d.items()).
  1. What does list(enumerate(['a', 'b', 'c'])) return?

    Answer`[(0, 'a'), (1, 'b'), (2, 'c')]`.
  2. How do you make enumerate start counting from 1 instead of 0?

    Answer`enumerate(iterable, start=1)`.
  3. Does enumerate work on a generator, or only on lists?

    AnswerAny iterable β€” generators, strings, file objects, etc., not just lists.