Python enumerate(): Index and Value Together
What you’ll learn
Section titled “What you’ll learn”- What
enumerateyields and why it is an iterator, not a list. - The
startparameter and how it reindexes without skipping items. - Pairing
enumeratewithzip, dicts, and file lines. - Why it beats a manual counter and the off-by-one traps it removes.
- When
enumerateis the wrong tool and a plain loop is better.
Summary
Section titled “Summary”enumerate(iterable, start=0) wraps any iterable and yields (index, value) pairs as you loop. The index is a counter that starts at start and increments by one per item; the iterable itself is unchanged. Because enumerate is lazy — it is an iterator — it costs no memory to hold all the pairs at once and works on generators and file objects the same as on lists. It removes the manual counter variable and the i += 1 line that seeds off-by-one bugs.
The problem it solves
Section titled “The problem it solves”The pattern “I need the position of each item” leads to two weak implementations: maintain i = 0 and i += 1 by hand, or call range(len(items)) and index back into the list with items[i]. Both are verbose and both invite off-by-one errors — forgetting to increment, incrementing in the wrong branch, or starting at the wrong value. range(len(items)) also forces items to be indexable, so it breaks on sets, generators, and file objects.
enumerate removes the counter entirely. The index comes for free, in lockstep with the value, with no bookkeeping to forget and no requirement that the source be a list. It also expresses intent: for lineno, line in enumerate(f, start=1) reads as “for each line number and line,” which is exactly what the code does.
How it works
Section titled “How it works”fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits): print(i, fruit)# 0 apple# 1 banana# 2 cherry
for i, fruit in enumerate(fruits, start=1): print(i, fruit)# 1 apple# 2 banana# 3 cherry
print(list(enumerate(fruits)))# [(0, 'apple'), (1, 'banana'), (2, 'cherry')]Each yielded item is a tuple (index, value). start changes only the first index emitted — the same items are visited in the same order. enumerate is an iterator: it produces pairs on demand and is exhausted after one pass, so list(enumerate(x)) materializes them if you need to reuse them.
enumerate works on any iterable, including ones you cannot index: generators, sets (note that set order is arbitrary), file objects, and the result of zip. To get an index over paired sequences, wrap zip:
names = ["Alice", "Bob"]ages = [30, 25]for i, (name, age) in enumerate(zip(names, ages), start=1): print(i, name, age)# 1 Alice 30# 2 Bob 25Realistic example
Section titled “Realistic example”OrdersPortal needs a numbered order receipt (lines counted from 1) and a way to report the line number of any failed payment in an order log file. Both are one-liners with enumerate.
from decimal import Decimal
def print_receipt(order_id, line_items): print(f"Receipt {order_id}") subtotal = Decimal("0") for n, (sku, qty, price) in enumerate(line_items, start=1): line_total = qty * price subtotal += line_total print(f" {n}. {sku} x{qty} ${line_total:.2f}") print(f" Subtotal: ${subtotal:.2f}")
line_items = [ ("WIDGET-01", 2, Decimal("9.99")), ("WIDGET-02", 1, Decimal("19.50")), ("SHIPPING", 1, Decimal("5.50")),]print_receipt("ORD-1001", line_items)# Receipt ORD-1001# 1. WIDGET-01 x2 $19.98# 2. WIDGET-02 x1 $19.50# 3. SHIPPING x1 $5.50# Subtotal: $44.98Line numbers from a log file, where a file object is iterable but not indexable:
def failed_payment_lines(path): with open(path, encoding="utf-8") as f: for lineno, line in enumerate(f, start=1): if "PAYMENT_FAILED" in line: yield lineno, line.strip()
# for lineno, text in failed_payment_lines("orders.log"):# print(f"line {lineno}: {text}")enumerate works here even though the file is consumed once and cannot be indexed.
Production patterns
Section titled “Production patterns”- Number user-facing output from 1: pass
start=1so receipts, ranked lists, and numbered steps start at 1 instead of 0. - Line numbers from a file:
enumerate(f, start=1)gives you the line number for free withoutreadlines(), and it streams the file instead of loading it. - Index over paired sequences:
enumerate(zip(...))to get a position alongside paired values. - Track a position into a parallel structure: keep
enumeratewhen you need to look up or mutate a sibling element by the same position.
Common mistakes
Section titled “Common mistakes”- Maintaining a manual
i += 1instead of usingenumerate— the exact off-by-one source it exists to remove. - Iterating with
range(len(items))and indexingitems[i]— verbose and breaks on non-indexable iterables. - Assuming
enumerate(d.items())yields(index, key, value):enumerate(d)yields(index, key);enumerate(d.items())yields(index, (key, value))and needs tuple unpacking. - Forgetting
enumerateis an iterator and is exhausted after one pass — storelist(enumerate(x))if you need to iterate twice. - Calling
enumerateon a dict expecting key/value pairs — iterated.items()and enumerate that instead.
When to use it and when not to
Section titled “When to use it and when not to”Use enumerate when:
- You need each item and its position together.
- You are numbering output, counting lines, or tracking an index for sibling lookups.
- The source is not a list (generators, files) but you still want a position.
Avoid enumerate when:
- You only need the values — just iterate directly (
for item in items). - You need the index to compute something rather than to track position — consider
rangeor a comprehension. - You are pairing two sequences position-by-position —
zipis the right tool; addenumerateonly if you also need a counter.
Compatibility
Section titled “Compatibility”enumerate is a built-in, available since Python 2.3. The start parameter was added in Python 2.6/3.0 and is present on every supported release including 3.9 through 3.14. It works on any iterable.
Interview questions
Section titled “Interview questions”-
What does
list(enumerate(['a', 'b', 'c']))return, and what type isenumerateitself? It returns[(0, 'a'), (1, 'b'), (2, 'c')].enumerateis an iterator — it yields(index, value)tuples one at a time and is exhausted after one pass, so converting withlist()materializes the pairs. -
How do you make
enumeratestart counting from 1, and does that skip the first item? Passstart=1:enumerate(iterable, start=1).startchanges only the first index emitted, not which items are visited — every item is still iterated in order, just numbered from 1. -
What does
enumerate(d)yield for a dictd, and how do you get index, key, and value together? Iterating a dict yields its keys, soenumerate(d)yields(index, key). To get all three, iterate the items and enumerate those:for i, (key, value) in enumerate(d.items()). -
Senior scenario: a codebase has many loops written as
for i in range(len(items)): value = items[i]. What are the problems, and what would you change?range(len(items))plus indexing is verbose, forcesitemsto be indexable (so it breaks on sets, generators, and file objects), and separates the index from the value so the intent is hidden. If only the value is needed, iterate directly:for value in items. If both are needed, useenumerate(items). Reserverange(len(...))for the rare case where you genuinely need the integer index as a value — for example, to mutate a list in place at that position. The refactor is mechanical, removes a class of off-by-one bugs, and makes the loop readable on non-list iterables.
Key takeaways
Section titled “Key takeaways”enumerateyields(index, value)pairs and is itself an iterator.startreindexes without skipping items.- It works on any iterable, not just lists.
- Use
enumerate(zip(...))for an index over paired sequences. - Skip it when you only need the values — iterate directly.
Related pages
Section titled “Related pages”- zip — pairing sequences; combine with
enumeratefor indexed pairs - List comprehensions — when you want a derived list rather than a loop
- splat operator —
*args/**kwargs, often paired withenumeratein logging - walrus operator — inline assignment inside loops