enumerate()
enumerate()
Section titled βenumerate()βWhat it is
Section titled βWhat it isβ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.
Before this feature
Section titled βBefore this featureβfruits = ["apple", "banana", "cherry"]
i = 0for fruit in fruits: print(i, fruit) i += 1After this feature
Section titled βAfter this featureβ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')]Why this is better
Section titled βWhy this is betterβ- No manual counter to forget updating:
i += 1is exactly the kind of off-by-one bug source thatenumerateeliminates. - 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:enumerateis itself an iterator β it doesnβt build a list of all the pairs upfront unless you explicitly convert it withlist(...).
Key notes / edge cases
Section titled βKey notes / edge casesβenumerateworks 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
startparameter 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, soenumerate(d)gives(index, key), not(index, key, value); for indexed key/value pairs youβd needenumerate(d.items()).
Quick practice
Section titled βQuick practiceβ-
What does
list(enumerate(['a', 'b', 'c']))return?Answer
`[(0, 'a'), (1, 'b'), (2, 'c')]`. -
How do you make
enumeratestart counting from 1 instead of 0?Answer
`enumerate(iterable, start=1)`. -
Does
enumeratework on a generator, or only on lists?Answer
Any iterable β generators, strings, file objects, etc., not just lists.