enumerate() is the Python built-in that lets you loop over an iterable and get a counter alongside each item: for index, item in enumerate(items):. By default the counter starts at 0, and you can change that with start, as in enumerate(items, start=1).
The basic syntax of enumerate in Python
The official signature is:
enumerate(iterable, start=0)
The Python documentation describes it this way: it returns an enumerate object, and each call to that object's __next__() method returns a tuple containing a count (from start, which defaults to 0) and the values obtained from iterating over iterable. The iterable can be a sequence, an iterator, or any other object that supports iteration.
The most common use is a for loop that unpacks each tuple into two names:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Example output:
0 apple
1 banana
2 cherry
The first name receives the count and the second receives the item. You can pick any names, but descriptive ones such as index and fruit are easier to read than i and x once the loop body grows.
What enumerate actually returns
Calling enumerate() does not build a list. It returns an iterator that produces one (count, value) tuple at a time. To see the pairs, convert it with list(). This is the example from the Python documentation:
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
Because it is an iterator, it can be consumed only once. If you call list() on the same enumerate object twice, the second list is empty. Create a new enumerate(...) call whenever you need to loop again.
pairs = enumerate(["a", "b"])
print(list(pairs)) # [(0, 'a'), (1, 'b')]
print(list(pairs)) # []
The documentation also gives code that behaves the same way, which makes the mechanism easy to see:
def enumerate(iterable, start=0):
n = start
for elem in iterable:
yield n, elem
n += 1
That is all enumerate() does: keep a counter, advance it by 1 for every item, and yield the counter together with the item. The built-in itself is not a Python generator, but it produces the same sequence of pairs.
How to start enumerate at 1
Use the start argument. People often want 1-based numbering for output that a person will read, such as a numbered list:
tasks = ["write report", "send invoice", "book flight"]
for number, task in enumerate(tasks, start=1):
print(f"{number}. {task}")
Example output:
1. write report
2. send invoice
3. book flight
The documentation shows the same thing with list(enumerate(seasons, start=1)), which returns [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]. Note that start only changes the counter. It does not skip items, and it does not change how the original list is indexed. If you use the counter to look something up, such as tasks[number], a start of 1 will be off by one and will raise IndexError on the last item. For the f-string syntax used above, see Python f-strings explained.
Enumerate with a list, a tuple or a string
Any iterable works. A tuple behaves like a list, and a string yields one character per step:
for position, letter in enumerate("cat"):
print(position, letter)
Example output:
0 c
1 a
2 t
A common practical use is finding where something occurs. This loop prints the position of every vowel in a word:
word = "banana"
for position, letter in enumerate(word):
if letter in "aeiou":
print(position, letter)
It prints positions 1, 3 and 5, each with the letter a. If you only need the first position of a value, word.index("a") is shorter. Use enumerate() when you need every position, or when you need to test a condition on each item. The pattern of filtering inside a loop is covered in Python for loop with an if condition.
Enumerate a dictionary
Looping over a dictionary yields its keys, so enumerate(my_dict) pairs a counter with each key. To get the counter, the key and the value together, enumerate the .items() view and unpack the inner tuple with parentheses:
prices = {"tea": 3.5, "coffee": 4.0, "juice": 5.25}
for index, (name, price) in enumerate(prices.items(), start=1):
print(index, name, price)
Example output:
1 tea 3.5
2 coffee 4.0
3 juice 5.25
The parentheses matter. Without them, for index, name, price in ... fails with ValueError: not enough values to unpack (expected 3, got 2), because each item from enumerate() is a two-element tuple whose second element is itself a pair.
Enumerate lines in a file
An open text file is an iterable of lines, so enumerate() gives you line numbers without reading the whole file into memory:
with open("notes.txt", encoding="utf-8") as handle:
for line_number, line in enumerate(handle, start=1):
print(line_number, line.rstrip())
This works because enumerate() only asks for the next item when the loop needs it. A fuller walkthrough of reading files is in Python read file line by line.
Enumerate vs range(len())
Before enumerate() existed, the usual way to get an index was to loop over range(len(items)) and look each item up by position. PEP 279, which added the function in Python 2.3 and now has the status Final, says it introduces enumerate() "to simplify a commonly used looping idiom". Compare the two forms:
# index-based
for i in range(len(fruits)):
print(i, fruits[i])
# enumerate
for i, fruit in enumerate(fruits):
print(i, fruit)
Both print the same output. The enumerate() version has no second lookup and no chance of using the wrong variable. It also works when the iterable has no length or cannot be indexed, such as a generator or an open file, where len() and items[i] both fail. Use range(len(...)) only when you really need to assign back to items[i] by position and the index arithmetic itself is the point.
Enumerate in a list comprehension
You can use enumerate() inside a comprehension as well. This builds a list of the positions of every negative number:
values = [4, -1, 7, -3, 0]
negative_positions = [index for index, value in enumerate(values) if value < 0]
print(negative_positions) # [1, 3]
This is the same unpacking as in the loop, written in one line. See Python list comprehension for the full syntax.
Common mistakes with enumerate
- Unpacking into the wrong number of names. Each item is a pair.
for item in enumerate(fruits)gives you the whole tuple, such as(0, 'apple'), initem. That is valid, but it is rarely what you meant. - Swapping the order. The count always comes first. Writing
for fruit, index in enumerate(fruits)puts the number infruitand the text inindex, and nothing raises an error. - Passing the start value positionally by accident.
enumerate(items, 1)works, butstart=1says what the number means. - Reusing a consumed enumerate object. As shown above, the second pass over the same object yields nothing.
- Adding or removing items from the list while looping over it. The counter keeps going by 1 whether or not the list changed, so it can drift from the item's real position. Loop over a copy (
enumerate(items[:])) or build a new list instead. - Calling
enumerate()with no argument. This raises aTypeErrorbecauseiterableis required.
If enumerate gives you an unexpected result
Print list(enumerate(your_iterable)) on a small sample. That shows exactly which pairs the loop receives, and it usually makes an unpacking or ordering mistake obvious. If the iterable is itself an iterator, such as a generator or a file, remember that printing it this way consumes it, so build the sample from a fresh copy.
Frequently asked questions
- What does enumerate return in Python?
- enumerate() returns an enumerate object, which is an iterator. Each step of it produces a tuple of (count, value), where the count starts at the start argument (default 0) and the value comes from the iterable you passed in. Wrap it in list() to see all the pairs at once.
- Can enumerate start at 1?
- Yes. Pass start=1, as in enumerate(items, start=1). The count begins at 1 and increases by 1 for each item. The items themselves are not changed or skipped; only the numbers differ.
- Does enumerate work on strings, tuples and dictionaries?
- It works on anything you can loop over. A string gives one character per step, a tuple gives its elements, and a dictionary gives its keys. Use enumerate(my_dict.items()) if you need the index together with each key and value.
- Is enumerate faster than range(len(items))?
- This article did not benchmark it, so no speed claim is made. The practical reason to prefer enumerate is that it is shorter, avoids a separate items[i] lookup, and works on iterables that have no len() or indexing, such as generators and open files.