capypad
0 day streak
python / beginner
Snippet

Tracking Index with enumerate()

The enumerate() function is used when you need to loop through a list but also want to know the position (index) of the current item. It returns both the index and the value at the same time.

snippet.py
python
1
2
3
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Breakdown
1
fruits = [...]
A standard list of strings representing fruits.
2
for index, fruit in enumerate(fruits):
Starts a loop where 'index' gets the position (0, 1, 2) and 'fruit' gets the value.
3
print(index, fruit)
Outputs the numerical index followed by the fruit name.