Using enumerate() function gives you back two loop variables. The count of the current iteration and the value of the item at the current iteration.
The enumerate()
function in Python is used to loop over an iterable while keeping track of the index or position of the current item. This is commonly used with a for
loop to iterate over a list or other iterable while also accessing the current index or position of each item.
for index,subj in enumerate(subjects):
print(index,subj)
Just like with a normal for loop, the loop variables can be named whatever you want them to be named.
Example enumerate for loop in Python
Simple example code use count and value, but they could be named i and v or any other valid Python names.
items = ['Cricket', 'Tennis', 'Football']
for i, v in enumerate(items):
print(i, v)
Output:
Another example
Python gets indexed in for cycle.
my_list = [0, 1, 2, 3, 4]
for idx, val in enumerate(my_list):
print('{0}: {1}'.format(idx, val))
Output:
0: 0
1: 1
2: 2
3: 3
4: 4
Do comment if you have any doubts or suggestions on this Pytho 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.