Skip to content

Python enumerate(): Index and Value Together

  • What enumerate yields and why it is an iterator, not a list.
  • The start parameter and how it reindexes without skipping items.
  • Pairing enumerate with zip, dicts, and file lines.
  • Why it beats a manual counter and the off-by-one traps it removes.
  • When enumerate is the wrong tool and a plain loop is better.

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 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.

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 25

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.98

Line 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.

  • Number user-facing output from 1: pass start=1 so 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 without readlines(), 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 enumerate when you need to look up or mutate a sibling element by the same position.
  • Maintaining a manual i += 1 instead of using enumerate — the exact off-by-one source it exists to remove.
  • Iterating with range(len(items)) and indexing items[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 enumerate is an iterator and is exhausted after one pass — store list(enumerate(x)) if you need to iterate twice.
  • Calling enumerate on a dict expecting key/value pairs — iterate d.items() and enumerate that instead.

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 range or a comprehension.
  • You are pairing two sequences position-by-position — zip is the right tool; add enumerate only if you also need a counter.

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.

  1. What does list(enumerate(['a', 'b', 'c'])) return, and what type is enumerate itself? It returns [(0, 'a'), (1, 'b'), (2, 'c')]. enumerate is an iterator — it yields (index, value) tuples one at a time and is exhausted after one pass, so converting with list() materializes the pairs.

  2. How do you make enumerate start counting from 1, and does that skip the first item? Pass start=1: enumerate(iterable, start=1). start changes only the first index emitted, not which items are visited — every item is still iterated in order, just numbered from 1.

  3. What does enumerate(d) yield for a dict d, and how do you get index, key, and value together? Iterating a dict yields its keys, so enumerate(d) yields (index, key). To get all three, iterate the items and enumerate those: for i, (key, value) in enumerate(d.items()).

  4. 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, forces items to 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, use enumerate(items). Reserve range(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.

  • enumerate yields (index, value) pairs and is itself an iterator.
  • start reindexes 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.
  • zip — pairing sequences; combine with enumerate for indexed pairs
  • List comprehensions — when you want a derived list rather than a loop
  • splat operator — *args/**kwargs, often paired with enumerate in logging
  • walrus operator — inline assignment inside loops