capypad
0 day streak
python / beginner
Snippet

Looping with Index using enumerate()

When you need both the position (index) and the value of items in a list during a loop, enumerate() is the most efficient and readable way to do it.

snippet.py
python
1
2
3
items = ['apple', 'banana']
for index, val in enumerate(items):
print(index, val)
Breakdown
1
items = ['apple', 'banana']
Define a list containing two string elements.
2
for index, val in enumerate(items):
Loop through the list, assigning the count to 'index' and the item to 'val'.
3
print(index, val)
Print both the current index and the item value together.