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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap