enumerate() provide index and value to the for loop


Sat Jan 15 2022 19:30:51 GMT+0000 (UTC)

Saved by @alba #python #iteration #enumerate #list

colors = ['red', 'green', 'blue']
for idx, color in enumerate(colors):
	print(idx, color)
> 0 red
> 1 green
> 2 blue

If we need to access the index of the item while iterating a list, we use the built-in enumerate()function to provide the index and the value to a forloop: