Sub topic 4
Getting index and value with enumerate
This chapter shows how enumerate works, what it returns, where it fits, and which mistakes come up most often. It assumes you can already do the following:
- Write a
forloop over a list. - Unpack a tuple into several names, as in
a, b = (1, 2). - Explain why
range(len(seq))makes loops awkward. The earlier chapters in this tutorial cover all of this.
The start argument of enumerate has its own chapter. Here the counter always begins at 0.
What enumerate does
Many loops need two things at once: the position of an item and the item itself. enumerate supplies both. It takes any iterable and produces (index, value) pairs. A for loop can unpack each pair into two names.
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 second loop never indexes into the list. It cannot go out of range, and the loop header says what each name means. index is the position and fruit is the item.
What enumerate returns
Calling enumerate(fruits) does not build a list of pairs. It returns an enumerate object, which is an iterator. It produces one pair each time something asks for the next one, so it uses almost no memory even for a very long input.
You can watch this happen with next():
letters = enumerate(["a", "b"])
print(next(letters))
print(next(letters))
try:
next(letters)
except StopIteration:
print("no more pairs")The output is:
(0, 'a')
(1, 'b')
no more pairsA for loop does exactly this behind the scenes. It calls next() until StopIteration is raised, then ends quietly.
The equivalent generator function shows the whole mechanism in four lines:
def my_enumerate(iterable, start=0):
n = start
for item in iterable:
yield n, item
n += 1
for i, ch in my_enumerate("hey"):
print(i, ch)The built-in is implemented in C and is faster. The behavior is the same: it asks the inner iterable for one item, pairs it with the current count, and then increments the count.
Unpacking the pair
Each value produced by enumerate is a two-item tuple. The names in the loop header are matched to the tuple's positions, so the order matters. The index always comes first.
fruits = ["apple", "banana", "cherry"]
for pair in enumerate(fruits):
print(pair)
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")The first loop binds the whole tuple to one name and prints (0, 'apple'), (1, 'banana'), (2, 'cherry'). This is legal and sometimes useful, but it forces you to write pair[0] and pair[1] in the body. Unpacking in the header is almost always clearer.
If you swap the names, nothing fails. Python just binds them in the wrong order:
for fruit, index in enumerate(["apple", "banana"]):
print(fruit, index)This prints 0 apple and 1 banana. The variable named fruit holds a number. Because Python raises no error, the mistake only shows up later, for example when you call a string method on an integer. Name the index first and read the header aloud when something looks off.
What you can enumerate
enumerate accepts any iterable, not just lists. The index counts how many items have been produced so far.
import io
# A string yields characters
for i, ch in enumerate("abc"):
print(i, ch)
# A tuple works like a list
for i, n in enumerate((10, 20, 30)):
print(i, n)
# A file-like object yields lines
data = io.StringIO("alpha\nbeta\ngamma\n")
for n, line in enumerate(data):
print(n, line.rstrip())
# A generator yields whatever it computes
squares = (x * x for x in range(4))
for i, sq in enumerate(squares):
print(i, sq)Files and generators are the interesting cases. Neither supports len() or seq[i], so the range(len(seq)) pattern cannot work on them at all. enumerate works because it needs only the ability to iterate.
Dictionaries
Enumerating a dictionary iterates over its keys, so the index is a running count, not a key.
prices = {"tea": 3, "coffee": 4, "milk": 2}
for i, key in enumerate(prices):
print(i, key, prices[key])
for i, (key, value) in enumerate(prices.items()):
print(i, key, value)The second loop uses a nested unpacking pattern. The parentheses split the inner (key, value) pair. A later chapter explains this form in detail when it combines enumerate with zip. For now, remember that the pattern in the loop header must mirror the shape of what is produced: an index, then one inner pair.
Dictionaries keep insertion order, so the index reflects the order in which keys were added. Do not treat that index as a stable identifier for a key.
Empty inputs
An empty iterable produces no pairs, so the loop body never runs. No special case is needed:
for i, x in enumerate([]):
print("never printed")
print("done")Using the index
The index is a plain integer. Three common uses follow.
Finding every position
list.index(value) returns only the first match. To find all matches, enumerate and filter:
words = ["to", "be", "or", "not", "to", "be"]
print(words.index("be"))
positions = [i for i, w in enumerate(words) if w == "be"]
print(positions)The output is 1, then [1, 5]. The comprehension form works because enumerate is an ordinary iterable and can appear after in in any comprehension.
Looking at a neighbor
Some questions compare an item with the one before it. Here the index is needed on purpose, so indexing the list is fine:
temps = [18, 21, 21, 25, 24]
for i, t in enumerate(temps):
if i > 0 and t > temps[i - 1]:
print(f"day {i} was warmer than the day before")This prints lines for day 1 and day 3. The i > 0 check matters. Without it, temps[i - 1] would be temps[-1] on the first pass, which silently reads the last item instead of raising an error.
Changing items in place
Assigning to the loop variable does not change the list. It only rebinds the name. To change the list, assign through the index:
scores = [70, 85, 90]
for s in scores:
s = s + 5
print(scores)
for i, s in enumerate(scores):
scores[i] = min(s + 5, 100)
print(scores)The first print shows [70, 85, 90], unchanged. The second shows [75, 90, 95]. If you only need a new list and not an edit in place, a comprehension such as [min(s + 5, 100) for s in scores] is usually simpler. Replacing items at their existing positions while you loop is safe because the list length does not change.
Edge cases and pitfalls
Changing the list length while looping
enumerate follows the underlying list as it changes, but the index does not adjust. If you delete an item, every later item shifts left and the loop skips one:
items = ["a", "", "", "b"]
for i, x in enumerate(items):
if x == "":
del items[i]
print(items)The result is ['a', '', 'b']. One empty string survives. After the first deletion, the second empty string moves into the slot the loop has already passed. Build a new list instead:
items = ["a", "", "", "b"]
items = [x for x in items if x]
print(items)Numbering after filtering
The order in which you combine filtering and enumerating decides what the numbers mean:
lines = ["intro", "", "body", "", "end"]
# Numbers count the non-empty lines only
for n, text in enumerate(t for t in lines if t):
print(n, text)
# Numbers are the original positions
for n, text in enumerate(lines):
if text:
print(n, text)The first loop prints indexes 0, 1, 2. The second prints 0, 2, 4. Choose the form that matches what the number should mean, for example "the nth match" versus "the line number in the source".
Enumerating an iterator uses it up
If the input is itself an iterator, such as a generator or a file, the loop consumes it. A second pass finds nothing. The chapter on one-shot iterators covers this in detail. The short version is to convert to a list first if you need two passes.
Not a sequence
An enumerate object is an iterator, not a list, so list operations on it fail:
e = enumerate(["x", "y"])
try:
e[0]
except TypeError as err:
print(err)
try:
len(e)
except TypeError as err:
print(err)
print(list(e))The first two messages are 'enumerate' object is not subscriptable and object of type 'enumerate' has no len(). Calling list(e) works and gives [(0, 'x'), (1, 'y')]. Do this when you need the pairs as data. For ordinary looping, do not.
Common errors at a glance
| Symptom | Cause | Fix |
|---|---|---|
| Value and index appear swapped | Header written as `for value, index in ...` | Put the index name first |
| `TypeError: 'int' object is not iterable` | Passed a number, such as `enumerate(5)` | Pass a sequence or use `range(5)` |
| `TypeError: 'enumerate' object is not subscriptable` | Indexed the result like a list | Wrap in `list(...)` or loop over it |
| Items skipped after `del` or `remove` | List shortened during the loop | Build a new list with a comprehension |
| List unchanged after the loop | Assigned to the loop variable | Assign with `seq[i] = ...` |
| Second loop over the same input is empty | Input was an iterator | Convert to a list once, then loop twice |
When not to use enumerate
enumerate is for cases where you need the position and the item. Skip it when:
- You only need the items. A plain
for item in seqis simpler. - You only need the position, such as
for i in range(n)repeating somethingntimes. - You need to walk two sequences together. That is the job of
zip, which the next chapters cover. - You need random access, such as jumping to
seq[i + 5]. Indexing a real sequence is fine there, but keepenumeratefor the loop itself.
A good test is to read the loop body. If the index appears only inside seq[i], you did not need it and a direct loop over the items would do. If the index is printed, compared, stored, or used to reach a different sequence, enumerate fits.
Summary of the working model
enumerate(iterable)returns an iterator of(index, value)tuples.- The counter starts at 0 here and increases by 1 for each item the inner iterable produces.
- A
forloop unpacks each tuple into the names in its header, index first. - It works on any iterable, including files and generators, which
range(len(seq))cannot handle. - The result is lazy and one-shot. Use
list()when you need the pairs as stored data.
Exercise
Write a loop using enumerate that prints the index of every item in ["x", "y", "x", "z", "x"] that equals "x". What does it print?
Show answer
for i, item in enumerate(["x", "y", "x", "z", "x"]): if item == "x": print(i). It prints 0, 2 and 4, each on its own line. Because enumerate pairs every item with its position, you get every match, whereas list.index would return only 0.
Exercise
What does for p in enumerate("hi"): print(p) print, and what type is p on each pass?
Show answer
It prints (0, 'h') and then (1, 'i'). The name p is bound to a two-item tuple on each pass, because the header does not unpack it. Writing for i, ch in enumerate("hi") would split each tuple into an integer and a one-character string.
Exercise
This code is meant to remove all negative numbers, but it leaves one in the result. Explain why and fix it. nums = [4, -1, -2, 5]; for i, n in enumerate(nums): if n < 0: del nums[i]
Show answer
After -1 at index 1 is deleted, the list becomes [4, -2, 5] and the loop moves on to index 2, so it never examines -2, which has shifted into index 1. The result is [4, -2, 5]. Fix it by building a new list: nums = [n for n in nums if n >= 0], which gives [4, 5].