DEV Community

BHUVANESH M
BHUVANESH M

Posted on • Edited on

5 1

The Day I Discovered enumerate()

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
csm18 profile image
csm

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!

Collapse
 
ceir profile image
Eric Garcia

enumerate() is without a doubt one of my favourite built-in python functions. Nice tip!

👋 Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay