It was a regular evening debug session. My code was working, but something about it just felt off. I was looping over a list—like always.
for i in range(len(my_list)):
value = my_list[i]
# Do something with value and i
Nothing wrong, right?
Except... I was starting to hate reading my own code.
It felt noisy. Clunky. Too much range(len(...))
. Too much manual indexing.
👀 The Realization
I stumbled across someone’s code online. It looked so clean, so elegant.
And that’s when I saw it:
for i, value in enumerate(my_list):
# Do something with i and value
Wait... what?
No range(len(...))
? No messy indexing?
✅ Cleaner
✅ More Pythonic
✅ No off-by-one errors
✅ Easier to read
✅ Less boilerplate
🧠 Why it works:
enumerate()
is a built-in Python function that returns both the index and the value of items in an iterable—in one shot.
No need to manually fetch the index. No need to worry about list length.
It’s like your loop suddenly gained superpowers.
💡 Bonus Tip:
You can even start the index from a custom number:
for i, val in enumerate(my_list, start=1):
print(f"Item {i}: {val}")
Perfect for user-facing counters. No more +1
hacks.
🚫 Never Again...
After that discovery, I made a quiet little promise:
No more range(len(...))
unless I really need it.
Now, it’s all enumerate()
, all day.
✨ Moral of the Story:
If you're reaching for
range(len(...))
, stop and ask yourself—
What would enumerate() do? 😎
📖 For more tips and tricks in Python 🐍, check out
Packed with hidden gems, Python's underrated features and modules are real game-changers when it comes to writing clean and efficient code.
Top comments (2)
I was also not aware about this builtin function.
Normally for looping through a list, I even don't use the
range(len(...))
.I use the old school while loop with a counter and increment for indexing.Thanks for sharing!
enumerate()
is without a doubt one of my favourite built-in python functions. Nice tip!