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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap