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.

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

for index, element in enumerate(list_of_cities):
    print(f'Index: {index}, Element: {element}')
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:

enumerate(iterable, start=0)

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


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:

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