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
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}")
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)