When writing clean and efficient Python code, small improvements can make a big difference. Still using range(len()) to loop through a list? Time to level up. There’s a better, cleaner way in Python: enumerate().
In this article, we’ll break down why range(len()) is a clunky relic of beginner code and how enumerate() makes your loops more readable, efficient, and elegant. Let’s ditch the old habits and write loops like pros.
We’ll cover practical examples, performance benefits, and real-world use cases.
What Is enumerate() In Python?
The Python enumerate() function is a built-in Python method that helps to simplify the process of looping. Therefore, in this, you can go through a sequence while keeping track of the index and the item at the same time.
Basic Syntax
enumerate(iterable, start=0)
- iterable: Any sequence like a list, tuple, or string.
- start: Optional. The index to start counting from (the default is 0).
Here is a quick example:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
Here is the output:
0 apple
1 banana
2 cherry
As you can see above, it is simple, clean, and readable. Now let’s compare that to using range(len()).
Why You Should Stop Using Range(Len())?
Here’s a traditional approach many beginners use:
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print(i, fruits[i])
While it works, this approach has downsides:
- Less readable: You have to mentally track both the index (i) and the item (fruits[i]). It’s an extra cognitive load.
- More prone to bugs: If you accidentally mismatch the index or use the wrong variable, errors pop in easily.
- Not Pythonic: Python emphasises readability and simplicity. The Zen of Python literally says: “Simple is better than complex.”
- Harder to refactor: If the sequence changes or becomes more complex, refactoring a range(len()) loop is messier.
- Slower in some contexts: While the speed difference is minor, enumerate() is sometimes slightly faster because it avoids repeated index lookups.
How To Master Enumerate() In Python?
Let’s break down some use cases to help you fully understand the power and how to use enumerate().
1. Basic Looping With Index
animals = ['cat', 'dog', 'rabbit']
for index, animal in enumerate(animals):
print(f"{index}: {animal}")
2. Starting From A Custom Index
for index, animal in enumerate(animals, start=1):
print(f"{index}: {animal}")
This is great when you want to display 1-based indexing instead of 0-based.
3. Looping Through Strings
word = "python"
for index, letter in enumerate(word):
print(f"Letter {index}: {letter}")
enumerate() works with any iterable, not just lists.
4. Unpacking Nested Lists With Index
data = [[1, 2], [3, 4], [5, 6]]
for index, (a, b) in enumerate(data):
print(f"Row {index}: a={a}, b={b}")
You can even combine unpacking and indexing in one clean line.
5. Using enumerate() In List Comprehensions
Although it is not directly usable in traditional list comprehensions, it helps when used within loops that build new lists. Here is a quick example:
names = ['Alice', 'Bob', 'Charlie']
indexed_names = [f"{i}: {name}" for i, name in enumerate(names)]
print(indexed_names)
Real-World Applications Of enumerate()
Here are a few real-world scenarios where enumerate() comes in handy.
1. Updating Values By Index
scores = [70, 85, 90, 75]
for i, score in enumerate(scores):
if score < 80:
scores[i] += 5
You can cleanly update items in-place without messy indexing (isn’t that easy?).
2. Debugging With Indexes
logs = ['OK', 'Fail', 'OK', 'Error']
for i, log in enumerate(logs):
print(f"Line {i}: {log}")
This technique is helpful in data processing, file reading, or logging.
3. Data Transformation
prices = [100, 200, 150]
discounted = [(i, p * 0.9) for i, p in enumerate(prices)]
As shown in the above example, you can pair each index with a calculated value.
When Not To Use enumerate()?
There are a few situations where enumerate() isn’t needed:
- When you don’t care about the index at all.
- When you’re working with dictionaries, use .items() instead.
- When using functions like map() or zip() that already pair values.
Does enumerate() Show Efficient Performance?
You might wonder— is enumerate() faster? In many cases, yes.
Here’s why and how enumerate() shows efficient performance:
- range(len(…)) has to evaluate the length each time.
- enumerate() creates an iterator that’s optimized for this task.
- The performance gain isn’t huge, but in large loops, it adds up.
Beginner To Pro (Refactoring Tips You Must Know)
Here are some tips to help you transition from range(len()) to enumerate() like a pro:
Example 1
Replace this:
for i in range(len(data)):
print(i, data[i])
With this:
for i, val in enumerate(data):
print(i, val)
Example 2
Replace this:
for i in range(len(words)):
words[i] = words[i].upper()
With this:
for i, word in enumerate(words):
words[i] = word.upper()
As you can learn above, small changes show big improvements.
Common Pitfalls With enumerate()
As a beginner, you may make many mistakes. Therefore, let’s clear up a few beginner mistakes.
Don’t Forget To Unpack:
for item in enumerate(fruits): # Wrong!
print(item)
This returns a tuple: (index, value). To fix:
for index, fruit in enumerate(fruits): # Correct
print(index, fruit)
Don’t Wrap enumerate() In List() Unless Needed:
list(enumerate(fruits)) # Avoid unless converting to a list intentionally
Final Thoughts
The Python enumerate() function is one of Python’s cleanest and most useful tools. Moreover, it helps you write more readable, less error-prone, and more logical code. Do you want to master Python? Check out the best Python certifications here!
So next time, if you catch yourself typing range(len()), remember there is a better way to do it. You can easily switch to enumerate()—your code (and future you) will thank you.