Python Enumerate: The Pythonic Loop
A simple function that separates beginner Python code from professional Python code.
The Problem
Often, you need to loop over a list, but you also need to know the index (position) of the current item.
fruits = ['apple', 'banana', 'mango']
for i in range(len(fruits)):
print(i, fruits[i])
This works, but it's hard to read. You are manually managing list indexing unnecessarily.
The Solution: Enumerate()
enumerate() takes a collection (like a list) and returns it as pairs of
(index, value).
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
print(index, fruit)
This is cleaner, faster, and less prone to "off-by-one" errors.
Advanced Usage: Changing the Start Index
By default, the counter starts at 0. But what if you are printing a numbered list for a user, starting at 1?
You don't need to do print(index + 1). Just pass the start argument.
rankings = ['Gold', 'Silver', 'Bronze']
for rank, medal in enumerate(rankings, start=1):
print(f"Rank {rank}: {medal}")
# Output:
# Rank 1: Gold
# Rank 2: Silver
# Rank 3: Bronze
Under the Hood
enumerate() returns an iterator, not a list. This means it is memory efficient. If
you need to see the pairs immediately, you can wrap it in list().
data = ['a', 'b', 'c']
print(list(enumerate(data)))
# Output: [(0, 'a'), (1, 'b'), (2, 'c')]