Get the index and value in a Python for loop

Use enumerate to iterate with a counter, set the starting number, and combine it with zip or dictionary items.

Best practices
Get the index and value in a Python for loop illustration

Use enumerate(items) when a loop needs both an element and its position. It yields (counter, value) pairs, starting at zero unless you supply start.

fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits):
    print(index, fruit)
# 0 apple
# 1 banana
# 2 cherry

for number, fruit in enumerate(fruits, start=1):
    print(number, fruit)

start=1 changes the displayed counter; it does not skip the first item or change the underlying list’s zero-based indices.

Prefer direct iteration when you need each value

# Valid, but requires an extra lookup on every iteration
for index in range(len(fruits)):
    print(index, fruits[index])

# Expresses the same intent more directly
for index, fruit in enumerate(fruits):
    print(index, fruit)

range(len(...)) still has uses when an algorithm specifically needs index arithmetic. enumerate also works with iterators and generators that have no length or indexing interface.

Combine a counter with paired values

names = ['Ada', 'Lin']
scores = [95, 88]

for name, score in zip(names, scores):
    print(name, score)

for index, (name, score) in enumerate(zip(names, scores)):
    print(index, name, score)

By default, zip stops at the shortest input. On Python 3.10+, use zip(names, scores, strict=True) if unequal lengths should be an error.

FAQ

Does enumerate create a list?

No. It is an iterator that produces pairs on demand, with small bookkeeping overhead rather than a second collection of all pairs. list(enumerate(items)) materializes the full result and uses memory accordingly.

Can I enumerate a dictionary?

Yes, but direct iteration yields keys. For a counter plus both keys and values, write for index, (key, value) in enumerate(mapping.items()):.

See Python built-in functions.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting