enumerate()
Adds a counter to any loop, giving you each item's position and the item itself, so you never need range(len(...)) again.
enumerate(iterable, start=0)enumerate() pairs every item with a number. In a loop, for i, item in enumerate(items): gives you the position in i and the item in item, at the same time.
It replaces the clumsy pattern for i in range(len(items)): item = items[i]. Use it for numbered lists, for line numbers when reading a file, and whenever you need to know where something was found.
Counting starts at 0, like list positions. For lists meant for people, pass start=1. Each round gives a pair (a tuple), which you split into two names right in the for line.
Parameters
| Parameter | What it is |
|---|---|
iterablerequired | Anything you can loop over: list, string, file, dictionary, generator… |
startoptional, default 0 | The first number to count from. |
Return value
An enumerate object that produces (number, item) pairs. Wrap it in list() to see them all.
Examples
1Number the items of a list
podium = ["Lena", "Omar", "Yuki"]
for place, name in enumerate(podium, start=1):
print(f"{place}. {name}")1. Lena 2. Omar 3. Yuki
2What enumerate() produces
print(list(enumerate("abc")))
print(list(enumerate(["x", "y"], start=10)))[(0, 'a'), (1, 'b'), (2, 'c')] [(10, 'x'), (11, 'y')]
3Find the positions of matching items
answers = ["yes", "no", "yes", "maybe", "yes"]
positions = [i for i, a in enumerate(answers) if a == "yes"]
print(positions)[0, 2, 4]
4Line numbers while reading a file
with open("todo.txt") as f:
for number, line in enumerate(f, start=1):
print(f"{number:>2}: {line.strip()}")1: buy milk 2: call the bank 3: water the plants
:>2 lines the numbers up on the right, which keeps longer files tidy.
5Change items in place
prices = [10.0, 24.5, 8.0]
for i, price in enumerate(prices):
prices[i] = round(price * 1.2, 2)
print(prices)[12.0, 29.4, 9.6]
Changing price alone would not affect the list; you need the position i to write the new value back.
Common mistakes
Forgetting to unpack the pair
With one name in the for line, you get the whole (number, item) tuple. Use two names.
for item in enumerate(["tea", "jam"]):
print(item)
for i, item in enumerate(["tea", "jam"]):
print(i, item)(0, 'tea') (1, 'jam') 0 tea 1 jam
Swapping the order of the names
The number comes first: for i, item in enumerate(...). Writing for item, i in ... gives each name the wrong value.
for name, i in enumerate(["Ana"]):
print("name:", name, "| i:", i)name: 0 | i: Ana
Questions people ask
How do I get the index in a for loop in Python?
for i, item in enumerate(items):. Add start=1 to count from one.
How do I use enumerate with a dictionary?
for i, (key, value) in enumerate(d.items()):. The brackets unpack the key-value pair.
How do I use enumerate and zip together?
for i, (a, b) in enumerate(zip(list1, list2)):.