Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python enumerate: Indexed Loops Without Counters

Python's enumerate function returns index-value pairs, supports a custom start, and simplifies indexed loops without manual counters.

~3 min readPython
#enumerate#Python loops#iteration#indexing
Illustration of Python enumerate pairing list items with their index numbers in a loop.

Python's built-in enumerate function is the standard way to iterate over an iterable while keeping track of the current index. It returns an enumerate object that yields (index, item) pairs as you loop. This eliminates the need to maintain a separate counter variable or call range(len(iterable)).

How enumerate Works and Why It Exists

When you need both the element and its position, the naive approach is to use a manual counter:

python
fruits = ["apple", "banana", "cherry"] i = 0 for fruit in fruits: print(i, fruit) i += 1

This works but requires a separate variable that must be incremented in the loop body. The enumerate function removes that bookkeeping by returning an iterator that produces (index, item) tuples:

python
for i, fruit in enumerate(fruits): print(i, fruit)

The first value is the index, the second is the item from the iterable. The loop variable unpacking happens automatically, which makes the intent clearer and reduces the chance of forgetting to increment the counter.

The start Parameter and Its Use Cases

enumerate accepts an optional second argument, start, which controls the initial index. The default is 0, but you can begin at any integer:

python
for i, line in enumerate(lines, start=1): print(f"{i}: {line}")

This is useful when you want line numbers in a file, or when you need a 1-based index for display or reporting. The start value only affects the first index; subsequent indices are incremented by 1 as usual.

Unpacking enumerate Results in Loops

The most common pattern is to unpack the tuple directly in the for statement. If you need only the index, you can use an underscore for the value:

python
for i, _ in enumerate(items): print(i)

If you need only the value, you can ignore the index with _:

python
for _, value in enumerate(items): print(value)

If you need both, the tuple unpacking is straightforward. You can also collect the results into a list of tuples:

python
indexed = list(enumerate(["a", "b", "c"])) # [(0, 'a'), (1, 'b'), (2, 'c')]

This is helpful when you need to pass the indexed pairs to another function or store them for later.

When to Prefer enumerate Over range(len())

A common alternative is for i in range(len(sequence)) and then access sequence[i]. That approach is more verbose and requires an extra lookup. It also fails for iterables that do not support indexing, such as generators or sets. enumerate works on any iterable, not just sequences. Compare:

python
# Using range(len()) for i in range(len(names)): print(i, names[i]) # Using enumerate for i, name in enumerate(names): print(i, name)

The second version is more readable and avoids the index lookup. It also works on any iterable, so you can use it with a generator expression or a file object.

Common Mistakes and Their Corrections

One mistake is to use enumerate with a generator and then try to iterate over the result more than once. enumerate returns an iterator, so it can only be consumed once; if the underlying iterable is a generator, that generator is consumed too. If you need to iterate multiple times, convert the result to a list first.

Another mistake is to forget that enumerate yields tuples, so if you try to assign the result to a single variable, you get a tuple, not separate values:

python
for pair in enumerate(items): print(pair) # (0, 'a')

If you need the index and value separately, unpack them. Also, be careful when using start with a non-integer value; enumerate expects an integer and will raise a TypeError if you pass a float or string.

Memory and Performance Characteristics of enumerate

enumerate is lazy: it does not create a list of tuples in memory. It returns an iterator that generates each pair on demand. This makes it memory-efficient for large iterables. The overhead per iteration is small: enumerate produces one tuple per item and increments an internal index, without requiring you to update a counter in the loop body. For most loops, the performance difference between enumerate and a manual counter is negligible. The main benefit is readability and reduced risk of off-by-one errors.

Using enumerate With Other Iterables and Generators

Because enumerate works on any iterable, you can use it with generators, file objects, and custom iterators. For example, to read lines from a file with line numbers:

python
with open("data.txt") as f: for line_no, line in enumerate(f, start=1): print(line_no, line.strip())

This pattern is common in log processing and configuration parsing. It also works with infinite iterators, though you must ensure the loop terminates.

When you need to combine enumerate with zip, use enumerate on the zipped result to number each pair:

python
for i, (name, score) in enumerate(zip(names, scores), start=1): print(i, name, score)

The key is that enumerate does not change the nature of the underlying iterable; it only adds an index.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.