Topic 62 of 64
Enumerate List
Overview
enumerate() adds an index counter to any iterable, returning (index, value) pairs. It eliminates the need for manual index variables and is the Pythonic way to iterate with indices — very common in interview solutions.
Syntax
python
fruits = ["apple", "banana", "cherry"]
# Without enumerate (not Pythonic)
for i in range(len(fruits)):
print(i, fruits[i])
# With enumerate (Pythonic)
for i, fruit in enumerate(fruits):
print(i, fruit)
# Custom start index
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# 1. apple
# 2. banana
# 3. cherryCommon Pitfalls
- enumerate() returns an enumerate object (iterator) — convert to list() only if you need random access.
- The 'start' parameter shifts the counter but not the actual index into the list — element access still uses the original index.
- Interview tip: enumerate() is preferred over range(len(x)) in all cases — it's more readable, avoids off-by-one errors, and works with any iterable (not just indexable sequences).
Real-World Example
Find and report the positions of all duplicates in a list
example
python
def find_duplicate_positions(items: list) -> dict:
positions: dict = {}
for i, item in enumerate(items):
positions.setdefault(item, []).append(i)
return {k: v for k, v in positions.items() if len(v) > 1}
data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
print(find_duplicate_positions(data))
# {'apple': [0, 2, 5], 'banana': [1, 4]}