Python Reference ยท Built-in Functions
Python enumerate() function
Reference for Python enumerate(): loop with an automatic counter, set the start value, build dictionaries from it, and avoid range(len()) patterns.
enumerate() wraps an iterable and produces (index, item) pairs. It is the standard way to get a counter while looping, replacing manual i += 1 bookkeeping and the old for i in range(len(seq)) pattern.
The result is a lazy iterator: pairs are created as you consume them, so it works with any iterable, including generators and files, without building a list.
for i, color in enumerate(["red", "green"]): print(i, color) # 0 red # 1 green
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
enumerate(iterable, start=0)
| Name | Description |
|---|---|
iterable |
Any object you can iterate over: list, tuple, string, dictionary, generator, file. |
start |
The number given to the first item. Default 0. Any integer works, including negatives. |
Return value: an enumerate iterator that yields tuples (count, item).
Raises: TypeError if iterable is not iterable or start is not an integer (floats are rejected).
Usage notes
- Iterator, not a list. Wrap it in
list()to see everything at once. After one pass it is exhausted, as the second example shows. startchanges only the label. It does not skip items;enumerate(items, 1)still visits every item, just numbering from 1.- Prefer it over
range(len()).for i, x in enumerate(xs)avoids indexing mistakes and also works for iterables that have no length. - Modify with care. Changing a list's length while enumerating it can skip or repeat items. To change items in place, assign by index:
xs[i] = new. - Unpacking. The tuple can be unpacked directly in the
forheader, and nested unpacking such asfor i, (a, b) in ...works when items are pairs. - Dictionaries enumerate their keys. Use
enumerate(d.items())for pairs. - Combine with
zip()to walk several sequences:for i, (a, b) in enumerate(zip(xs, ys)). - Counting beyond int. The counter switches to arbitrary-size integers automatically, so very long iterations do not overflow.