python / beginner
Snippet
Indexing Loops with enumerate()
The enumerate() function adds a counter to an iterable and returns it as an enumerate object. This is useful when you need the index of each item while looping through a list.
snippet.py
1
2
3
4
5
colors = ['red', 'green', 'blue']for index, color in enumerate(colors):print(index)print(color)
Breakdown
1
for index, color in enumerate(colors):
Starts a loop where 'index' gets the position and 'color' gets the item value.
2
print(index)
Prints the current numeric position starting from 0.