DEV Community

Cover image for Python's enumerate() Function() is a Game Changer
Sameer Qaiser
Sameer Qaiser

Posted on Edited on

Python's enumerate() Function() is a Game Changer

When I first started writing Python for loops, I used to do this:

fruits = ["apple", "banana", "cherry"]
index = 0
for fruit in fruits:
    print(f"{index + 1}. {fruit}")
    index += 1
Enter fullscreen mode Exit fullscreen mode

Then I discovered enumerate(). It gives you both the index and the item at the same time, without you having to manually track the counter.

fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits, start=1):
    print(f"{index}. {fruit}")
Enter fullscreen mode Exit fullscreen mode

It's cleaner, more readable, and saves you from off-by-one errors. It's one of those built-in functions that makes Python feel like a cheat code

Top comments (0)