values = ["a", "b", "c"]
for index, value in enumerate(values):
print(index, value)
# 0 a
# 1 b
# 2 c
When you use enumerate(), the function gives you back two loop variables:
- The index of the current iteration
- The value of the item at the current iteration
With enumerate(), you don’t need to remember to access the item from the iterable, and you don’t need to remember to advance the index at the end of the loop.
Python’s enumerate() has one additional argument that you can use to control the starting value of the count. By default, the starting value is 0 because Python sequence types are indexed starting with zero.
There are many times when you might not want the count from enumerate() to start at 0. For instance, you might want to print a natural counting number as an output for the user. In this case, you can use the start argument for enumerate() to change the starting count:
for index, value in enumerate(values, start=1):
print(count, value)
# 1 a
# 2 b
# 3 c