python / beginner
Snippet
Looping with Indices using enumerate()
The enumerate() function adds a counter to an iterable and returns it as an enumerate object. This allows you to track the current index while looping through a list without needing a manual counter variable.
snippet.py
1
2
3
fruits = ['apple', 'banana', 'cherry']for index, fruit in enumerate(fruits):print(index, fruit)
Breakdown
1
fruits = ['apple', 'banana', 'cherry']
Initialize a list containing three string elements.
2
for index, fruit in enumerate(fruits):
Start a loop that unpacks both the position (index) and the item (fruit) for each entry.
3
print(index, fruit)
Display the numeric index followed by the string value of the current item.