Access Index in For Loop


Access Index in For Loop in Python

To access index of the current element in a For Loop, use enumerate() builtin function. enumerate() allows us to access both the index, and the element during iteration.

Examples

In this example, we will take a list of strings, and iterate over the strings, and print both index and element.

Python Program

fruits = ['apple', 'banana', 'mango', 'cherry']

for index, fruit in enumerate(fruits):
    print(index, ':', fruit)

Output

0 : apple
1 : banana
2 : mango
3 : cherry

Summary

In this tutorial of Python Examples, we learned how to access index during iteration in a For Loop.