The Python enumerate() function adds a counter to iterable objects like a list. This method will allow you to loop over a list of items while keeping track of the index value in a separate variable.
enumerate(iterable, start=0)
The start is an optional argument for counting the index, the default value is zero.
Python enumerate list example
Simple example code use enumerate() to get a counter in a loop.
values = ["A", "B", "C"]
for count, value in enumerate(values):
print(count, value)
Output:
You can also pass a second argument to the enumerate()
function to specify the starting index, like this:
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
Using the enumerate()
function, you can avoid the need to manually keep track of the index while iterating over the list.
Comment if you have any doubts or suggestions on this Python enumerate topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.