Python enumerate: index, value and the start argument

Use Python enumerate to loop over values with their indices, number items from 1, and preserve original positions when slicing or filtering.

PythonBy
Published on

You need both a value and its position in the same loop. enumerate() provides them without a counter to update by hand. The trap comes when you change start and still treat the resulting number as a list index.

In short

enumerate(iterable, start=0) yields (count, value) pairs. For a list traversed from its beginning with the default start, that count matches the index. start=1 changes the numbering without skipping the first item or changing list indices. To preserve original positions when filtering, apply the filter after enumerate().

How do you get the index and value?

Write for index, value in enumerate(items): Python unpacks each pair into the two variables. The first count is zero, then it increases by one for each item.

pairs.py
items = ["kiwi", "fig", "kiwi"]for index, value in enumerate(items):    print(index, value)
Terminal
$ python3 pairs.py0 kiwi1 fig2 kiwi

The two occurrences of kiwi have different positions. Searching with items.index(value) answers a different question: where is the first occurrence of that value? It doesn't describe the current iteration.

If you only need the value, loop over the values directly. If you need numbers defined by a bound or a step, use range(). Choose enumerate() when you're consuming values and need to attach a counter to them.

Does start=1 skip the first item?

No. start sets the first count returned; the first value still comes from the beginning of the iterable you pass in.

start.py
items = ["kiwi", "fig", "kiwi"]print(list(enumerate(items, start=1)))print(list(enumerate(items, start=-2)))print(items[0])
Terminal
$ python3 start.py[(1, 'kiwi'), (2, 'fig'), (3, 'kiwi')][(-2, 'kiwi'), (-1, 'fig'), (0, 'kiwi')]kiwi

The counter can also start at a negative integer. It still advances by one. Use start=1 for numbering shown to a person; keep zero-based indices for access through items[index].

  1. items[0]'a'count 1
  2. items[1]'b'count 2
enumerate(['a', 'b'], start=1)

With this one-based start, using the count as an index would read the second item on the first iteration and eventually run past the end. Use the value the loop already gives you.

How do you preserve indices after slicing?

For a contiguous suffix, set start to the slice's starting position. A simple offset isn't enough when the slice skips positions.

slice.py
items = ["a", "b", "c", "d", "e"]print(list(enumerate(items[2:], start=2)))print(list(enumerate(items[::2])))print([(i, value) for i, value in enumerate(items) if i % 2 == 0])
Terminal
$ python3 slice.py[(2, 'c'), (3, 'd'), (4, 'e')][(0, 'a'), (1, 'c'), (2, 'e')][(0, 'a'), (2, 'c'), (4, 'e')]

items[2:] starts at index two and keeps every subsequent item, so counts two, three and four match the original list. items[::2] keeps positions zero, two and four, but enumerate() numbers them zero, one and two. It doesn't know where the sliced list came from.

The final expression traverses the source with its indices, then keeps every other position. This preserves the information you need without reconstructing a source index from a slice counter.

Should you filter before or after enumerate?

Filter after enumerate() to keep source positions. Filter before it to number only the selected items.

filter.py
values = [0, 8, 0, 8]print([(i, value) for i, value in enumerate(values) if value])print(list(enumerate(value for value in values if value)))print([values.index(value) for value in values if value])
Terminal
$ python3 filter.py[(1, 8), (3, 8)][(0, 8), (1, 8)][1, 1]

The nonzero values are at positions one and three. If you filter first, they become items zero and one in the new iterable. The last line shows why repeated calls to index() don't replace enumeration: both calls find the first occurrence of eight.

Decide what the number means before writing the condition. A source line number, a position in a selection and a displayed rank starting at one can all be useful. They aren't interchangeable.

Can you traverse the result twice?

An enumerate object is an iterator: consuming it advances its state.

iterator.py
pairs = enumerate(["a", "b"], start=1)print(next(pairs))print(list(pairs))print(list(pairs))
Terminal
$ python3 iterator.py(1, 'a')[(2, 'b')][]

The call to next() consumed the first pair. The first list() collects the remaining pairs; the second collects nothing. Creating another enumerate(items) allows another pass if items is a reusable list. If the source itself is an already-consumed iterator, replacing the wrapper won't rewind that source.

To traverse several sources together, read about different lengths with zip. Adding a counter to one source solves a different problem.

How can you use these indices in an exercise?

To mask the middle of a string, compare each index with the two regions to keep. The number must be a zero-based position here: display numbering would shift the boundaries.

mask.py
def mask_middle(text, keep):    result = []    for index, char in enumerate(text):        if index < keep or index >= len(text) - keep:            result.append(char)        else:            result.append("*")    return "".join(result)
print(mask_middle("bluebird", 2))print(mask_middle("owl", 2))print(mask_middle("kiwi", 0))print(repr(mask_middle("", 3)))
Terminal
$ python3 mask.pybl****rdowl****''

The left region satisfies index < keep, the right index >= len(text) - keep. If they meet or overlap, every character stays visible. With keep=0, no characters are kept; with an empty string, the loop has no iterations. This function assumes the exercise contract: keep is a nonnegative integer.

Python

mask_middle

8-bit

Implement mask_middle: preserve both ends and replace the middle with stars without changing the length. Check overlapping ends and spaces too.

Open the exercise

An index follows the source as iteration proceeds. Removing source items during the loop shifts positions: building a selection without deleting during traversal avoids that separate mistake.

Frequently asked questions

Does enumerate return a list?

No, it returns an iterator. list(enumerate(items)) consumes it to build a list of pairs. A for loop can consume it directly.

Can you use enumerate on a string?

Yes. It traverses the characters of a Python string. These are Unicode code points, not bytes or necessarily complete visible characters: a letter followed by a combining accent occupies two positions.

Can you change the counter step?

enumerate() has no step argument. To preserve every other source position, filter indices after enumeration; changing start won't do that.

Does enumerate protect against list changes?

No. It doesn't freeze the source. Avoid removing items from the list being traversed when you rely on their original positions.

Sources

Now write it yourself.