The built-in enumerate() function wraps an iterable and yields (index, item) pairs, so you get the position and the value in a single loop without maintaining a counter. Its signature is enumerate(iterable, start=0), and it returns a lazy iterator.
It replaces the older pattern of for i in range(len(items)) followed by items[i], which is longer and works only for sequences.
enumerateenumerateEach iteration unpacks one tuple into index and fruit. Because enumerate accepts any iterable, it also works with strings, tuples, dictionaries, sets, files and generators.
Use the start argument when counting should not begin at zero, for example for line numbers or numbered menus.
The start value only changes the numbers produced. It does not skip any items from the iterable.
Compare the three common approaches:
| Approach | Problem |
|---|---|
for i in range(len(xs)): xs[i] | Verbose, easy to get off by one, needs a sequence |
Manual i = 0 and i += 1 | Counter can be forgotten or misplaced |
for i, x in enumerate(xs) | Short, readable, works on any iterable |
enumerate is also memory friendly: it produces pairs one at a time rather than building a list.
The file is read lazily, so this works for very large files.
zipWhen you iterate over two sequences at once, wrap the pair in parentheses when unpacking.
enumerate returns an iterator, so it is consumed after one pass. Call list(enumerate(xs)) if you need the pairs again.enumerate(d.items()) to get pairs as well.start by keyword or position, and it must be an integer.enumerate is not limited to lists. With a string, each item is a character; with a dictionary, each item is a key; with a set, the order is arbitrary.
Sometimes you need the previous or next element. Use the index to reach it, but guard the boundaries.
For pairwise comparison, itertools.pairwise (Python 3.10+) is often cleaner.
| Goal | Code |
|---|---|
| Index and value | for i, x in enumerate(xs) |
| One-based numbering | for n, x in enumerate(xs, 1) |
| Dictionary of positions | {x: i for i, x in enumerate(xs)} |
| Positions of a match | [i for i, x in enumerate(xs) if x == target] |
| Skip the first item but keep counting | for i, x in enumerate(xs): if i == 0: continue |
enumerate create a list?No. It returns a lazy iterator that creates each (index, item) tuple on demand.
Yes, with enumerate(reversed(xs)), but the indices still count upward from zero. To keep original indices, use for i in range(len(xs) - 1, -1, -1) or compute len(xs) - 1 - i.
enumerate slower than range(len(...))?The difference is negligible in practice. Choose enumerate for clarity.
enumerate with a generator?Yes. It works with any iterable, including generators and file objects.
Use enumerate(iterable, start=0) whenever you need both an index and a value. It is more readable than manual counters, works with every iterable and stays lazy, which keeps memory usage low.