Python 3 reference · Built-in Functions
Python enumerate() Function
Loop over an iterable and get each item together with its index, as (index, item) pairs. The start number is configurable.
Python 3 Since 3.0
Syntax
enumerate(iterable, start=0)
Parameters
| Parameter | Description |
|---|---|
iterable |
Any iterable: a list, string, file, generator, … |
start optional |
The number to count from. Default: 0 |
Return value
An iterator of (index, item) tuples.
Examples
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(i, fruit)
Output
0 apple 1 banana 2 cherry
for rank, name in enumerate(["Ada", "Linus", "Grace"], start=1):
print(f"{rank}. {name}")
Output
1. Ada 2. Linus 3. Grace
words = ["red", "green", "blue", "green"]
print([i for i, w in enumerate(words) if w == "green"])
print(list(enumerate("ab")))
Output
[1, 3] [(0, 'a'), (1, 'b')]
Common mistakes
Avoid for i in range(len(items)): followed by items[i]. enumerate() is shorter, clearer and works with any
iterable, not just lists.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
range()· Create an immutable sequence of integers from start up to (but not including) stop, in steps. Used in for loops.zip()· Iterate over several iterables in parallel, producing tuples of their items. Stops at the shortest unless strict=True.iter()· Get an iterator from an iterable, or create one that calls a function until it returns a sentinel value.- Python For Loops · tutorial