Sub topic 4
Getting index and value with enumerate
This chapter assumes you can write a for loop over a list, know what a tuple is, and have seen unpacking such as a, b = (1, 2). Earlier chapters covered iterators and the problems with range(len(seq)). Here you will use enumerate to fix those problems.
What enumerate does
enumerate(iterable) takes any iterable and returns an iterator of (index, value) tuples. The index starts at 0 and goes up by one for each item. The loop header unpacks each tuple, so the body gets two named variables.
fruits = ["apple", "banana", "cherry"]
# Manual index
for i in range(len(fruits)):
print(i, fruits[i])
# With enumerate
for index, fruit in enumerate(fruits):
print(index, fruit)Both loops print the same three lines:
0 apple
1 banana
2 cherryThe enumerate version never indexes into the list. The loop reads each item from the iterable you gave it, and the counter is created for you.
How it works
You can see the pairs by turning the result into a list:
fruits = ["apple", "banana", "cherry"]
print(list(enumerate(fruits)))
# [(0, 'apple'), (1, 'banana'), (2, 'cherry')]Each for iteration receives one tuple. Writing index, fruit in the header unpacks it, which is the same unpacking as index, fruit = (0, 'apple').
enumerate is lazy. It does not build a list of pairs up front. It asks the underlying iterable for one item at a time and pairs it with the next number. This has two consequences:
- It works on anything iterable, not only lists. Strings, tuples, dictionaries, files, and generators all work.
- It uses almost no extra memory, even for very large inputs.
Typical uses
A common case is reporting the position of a problem, such as the line number of a bad record:
lines = ["id,name", "1,Ada", "oops", "3,Linus"]
for number, line in enumerate(lines):
if "," not in line:
print(f"line {number} is malformed: {line!r}")Another is finding every position where a condition holds:
values = [4, 0, 7, 0, 9]
zero_positions = [i for i, v in enumerate(values) if v == 0]
print(zero_positions)
# [1, 3]enumerate also works in comprehensions, as the second example shows. It is the usual way to get all matching positions. The list.index() method returns only the first match.
Common errors
The mistakes below come up often.
- Reversed order.
enumeratealways yields the index first. Writingfor fruit, index in enumerate(fruits)runs without error but gives you the number infruitand the text inindex. - Forgetting to unpack. With a single loop variable, you get the whole tuple:
```python for pair in enumerate(["a", "b"]): print(pair)
(0, 'a')
(1, 'b')
```
This is valid but rarely what you want. Unpack in the header.
- Assuming the index is a dictionary key. On a dictionary,
enumeratecounts the keys:
```python ages = {"Ada": 36, "Grace": 45}
for i, name in enumerate(ages): print(i, name)
0 Ada
1 Grace
```
To get keys and values together, use enumerate(ages.items()) and unpack with a nested pattern: for i, (name, age) in ....
- Using the index to change the list while looping. Assigning to
items[i]inside the loop is safe. Inserting or removing items shifts the positions thatenumerateis still counting through, and you will skip or repeat elements. Build a new list instead. - Reusing the result. The object
enumeratereturns is an iterator, so it can be consumed only once. A later chapter covers this in detail. If you need to loop twice, callenumerateagain on the original iterable.
When not to use enumerate
If you need only the values, loop over them directly with for fruit in fruits. If you need only the count, use len(). Use enumerate when the loop body uses both the position and the item.
Exercise
Exercise
Given words = ["red", "green", "blue", "green"], write a list comprehension using enumerate that produces the index of every occurrence of "green". What does it return?
Show answer
[i for i, w in enumerate(words) if w == "green"] returns [1, 3]. It checks every item and keeps the index of each match, unlike words.index("green"), which returns only 1.
Exercise
What does this code print, and why? for item in enumerate(["x", "y"]): print(item)
Show answer
It prints (0, 'x') and then (1, 'y'). There is only one loop variable, so each whole (index, value) tuple goes into item without being unpacked.