`enumerate()`: Index + Value in One Go
Published:
• Last updated:
• By Jeferson Peter
Python
The manual way
fruits = ["apple", "banana", "cherry"]
index = 0
for fruit in fruits:
print(index, fruit)
index += 1
# 0 apple
# 1 banana
# 2 cherry
Using enumerate
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
# 0 apple
# 1 banana
# 2 cherry
With custom start
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
# 1 apple
# 2 banana
# 3 cherry
Conclusion
enumerate()
saves you from writing extra lines to handle counters. It makes loops cleaner and more Pythonic.