Python: Access index/counter of a for loop iteration

In Python, we can access the index or counter of a for loop using the enumerate() function

Let's take a look at an example.

Example:
list_of_cities = ['Mumbai', 'Chicago', 'New York', 'Tokyo', 'Paris']

for index, element in enumerate(list_of_cities):
    print(f'Index: {index}, Element: {element}')
Output:
Index: 0, Element: Mumbai
Index: 1, Element: Chicago
Index: 2, Element: New York
Index: 3, Element: Tokyo
Index: 4, Element: Paris
Access index of a for loop iteration

From the documentation:

Syntax:
enumerate(iterable, start=0)

Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration.

Reference: https://docs.python.org/3/library/functions.html#enumerate

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!