Sub topic 8
Getting index and value with enumerate()
This chapter assumes you can write a basic for loop over a list, that you know range() and len(), and that you have seen tuples and unpacking such as a, b = (1, 2). Here you replace the range(len(...)) pattern with enumerate(), which hands you each position and its item together.
The problem enumerate() solves
Sometimes you need both an item and its position. The index-based way is to loop over range(len(...)) and look each item up:
colors = ["red", "green", "blue"]
for i in range(len(colors)):
print(i, colors[i])This works, but it has costs:
- The reader sees
iandcolors[i]and must work out that they belong together. - The loop only works on objects that support indexing. A generator or an open file has no
colors[i]. - You can make mistakes with the bounds, such as
len(colors) - 1, or index a different list than you measured.
enumerate() gives the same result directly:
colors = ["red", "green", "blue"]
for i, color in enumerate(colors):
print(i, color)Both loops print the same three lines:
0 red
1 green
2 blueWhat enumerate() actually returns
enumerate(iterable) returns an enumerate object. This is an iterator that produces one two-item tuple per element, in the form (index, item). The for i, color in ... line uses tuple unpacking to split each tuple into two names.
e = enumerate(["a", "b", "c"])
print(next(e)) # (0, 'a')
print(next(e)) # (1, 'b')
print(list(e)) # [(2, 'c')]
print(list(e)) # []The last two lines show two properties:
- The enumerate object is lazy. It builds each tuple only when the loop asks for the next one, so it does not copy your data.
- It is an iterator, so it can be consumed only once. After
list(e)has used up the remaining items, a secondlist(e)returns an empty list. If you need to loop twice, callenumerate()again on the original iterable.
The diagram shows one pass of the loop.
Choosing the starting number
By default the counter starts at 0. The optional second argument, start, changes it. It only changes the numbers produced. It does not skip any items.
colors = ["red", "green", "blue"]
for number, color in enumerate(colors, start=1):
print(f"{number}. {color}")This prints:
1. red
2. green
3. blueUse start=1 when the number is shown to people, such as in menus, line numbers or rankings. Keep the default of 0 when the number is used as a real list index.
The counter is not tied to the list's own indexes. If you start at 1, then colors[number] points at the wrong item, and for the last item it raises IndexError.
Pairs, not two separate values
Each step of the loop produces one tuple. If you use a single loop variable, you get the whole tuple:
for pair in enumerate(["x", "y"]):
print(pair)(0, 'x')
(1, 'y')A common mistake is to write the names in the wrong order. The index always comes first.
for item, i in enumerate(["x", "y"]): # wrong order
print(item, i)This runs without error. It prints 0 x and 1 y, because item receives the number and i receives the letter. The names are misleading, so any later code using them will break in confusing ways.
What you can enumerate
enumerate() accepts any iterable, not just lists. That is its main advantage over range(len(...)).
- Strings give each character with its position.
- Tuples and sets work like lists, but a set has no meaningful order.
- Files and generators work even though they have no
len()and cannot be indexed. - Dictionaries give their keys by default.
For a dictionary, you usually want both key and value. Use .items() and put parentheses around the inner pair so that unpacking matches the nested tuple (index, (key, value)):
ages = {"Ada": 36, "Grace": 45, "Linus": 28}
for i, (name, age) in enumerate(ages.items(), start=1):
print(i, name, age)1 Ada 36
2 Grace 45
3 Linus 28Without the parentheses, for i, name, age in ... would raise ValueError, because each tuple has only two items.
Combining with zip()
Earlier chapters showed zip(), which pairs items from several iterables. Combine it with enumerate() by wrapping zip() inside enumerate(). The inner tuple again needs its own parentheses.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 72]
for rank, (name, score) in enumerate(zip(names, scores), start=1):
print(rank, name, score)1 Ada 95
2 Grace 88
3 Linus 72Practical patterns
Reporting positions
Line numbers, row numbers and similar reports are the most common use:
lines = ["alpha", "", "gamma", ""]
for lineno, line in enumerate(lines, start=1):
if not line:
print(f"line {lineno} is empty")line 2 is empty
line 4 is emptyFinding every matching position
The list method .index() returns only the first match. To find all matches, enumerate and test each item. This is also a good place to use a comprehension, which a later chapter covers in detail:
temps = [18, 21, 25, 19, 30]
hot = [i for i, t in enumerate(temps) if t > 20]
print(hot) # [1, 2, 4]Updating items in place
Assigning to the loop variable does not change the list, because p is just a name bound to the item. To change the list, assign through the index:
prices = [10, 20, 30]
for i, p in enumerate(prices):
prices[i] = p * 2
print(prices) # [20, 40, 60]Changing the contents of existing positions is safe. What is unsafe is adding or removing items during the loop, which an earlier chapter explained. If you need to do that, build a new list instead.
Treating the first item differently
You can test the counter to special-case the first item, for example to print a separator:
words = ["one", "two", "three"]
for i, word in enumerate(words):
if i > 0:
print("-", end=" ")
print(word, end=" ")
print()one - two - three For this particular case, " - ".join(words) is simpler. Use the counter approach only when the first item needs real extra work.
When not to use enumerate()
enumerate() is the default choice when you need both index and item, but it is not always needed:
| Situation | Better choice |
|---|---|
| You need only the items | `for item in items:` |
| You need only the count of iterations | `for _ in range(n):` |
| You need to step by 2 or go backwards over indexes | `range(start, stop, step)` |
| You need to look at neighbours, such as `items[i + 1]` | `range(len(items) - 1)` or `zip(items, items[1:])` |
| You want to loop over two lists in step | `zip(a, b)` |
Use range(len(...)) when the index itself is the point, for example when you step through positions by 2 or work backward. In every other case, enumerate() reads better and also works on iterables without len().
Summary of behavior
enumerate(iterable, start=0)returns a lazy iterator of(counter, item)tuples.- The counter comes first and starts at
start. It does not depend on the real position in the source. - The result can be consumed only once.
- It works on any iterable, including files and generators.
- Wrap nested pairs, as in
enumerate(d.items()), in parentheses when unpacking:i, (k, v).
Exercise
Given words = ["apple", "kiwi", "banana", "fig"], write a loop that uses enumerate() with a human-friendly counter starting at 1 and prints only the entries whose word has more than 4 letters, in the form 2. banana. Which numbers are printed, and why does the counter for "banana" show 3 rather than 2?
Show answer
Code: for n, w in enumerate(words, start=1): then if len(w) > 4: then print(f"{n}. {w}"). It prints 1. apple and 3. banana. Counting happens for every item before the filter runs, so "apple" is 1, "kiwi" is 2 and "banana" is 3. The counter reflects position in the original list, not the number of printed lines.
Exercise
What does this code print, and what is the bug? colors = ["red", "green", "blue"] followed by for n, c in enumerate(colors, start=1): print(colors[n]).
Show answer
It prints green, then blue, and then raises IndexError: list index out of range on the third pass. The counter n runs 1, 2, 3, but valid indexes are 0, 1, 2. The fix is to print c directly, or to loop without start=1 if n is used as an index.