Indexed iteration
Need both a position and a value while looping over a sequence.
Python · Function
enumerate() pairs each item from an iterable with an incrementing count. The count starts at 0 by default or at the supplied start value.
Call enumerate() with an iterable to obtain a lazy iterator of pairs. Each pair contains a counter and the next value from the iterable; the counter begins at start, which defaults to 0, and advances as iteration proceeds.
enumerate(iterable, start=0)| Name | Type | Description |
|---|---|---|
iterable | iterable | Object to iterate over; it must support iteration. |
start | integer | Initial counter value; defaults to 0. |
An enumerate object whose iterator yields tuples containing a count and each value from iterable.
items = ["alpha", "beta", "gamma"]
for index, item in enumerate(items, start=1):
print(f"{index}: {item}")Print each item together with a one-based position.
Need both a position and a value while looping over a sequence.
Display user-facing positions that begin at one instead of zero.
Process a generator while retaining the number of items seen.
enumerate() returns an enumerate object, which is an iterator that yields tuples. Each tuple contains the current count and the corresponding value from the iterable.
Follow-up: What is the default first index? It is 0, unless a different start value is supplied.
The start argument sets the initial count and defaults to 0. For example, start=1 produces counts beginning at 1 while leaving the iterable's values unchanged.
Follow-up: Can start be negative? Yes; it is used as the initial count, so negative values produce negative initial indices.
enumerate() accepts a sequence, an iterator, or another object that supports iteration. It advances through that object and yields one count-value tuple per item.
Follow-up: What happens with a generator? enumerate() consumes it lazily as the returned iterator is advanced.
iter()next()zip()range()