Python enumerate for loop | Example code

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.

for index,subj in enumerate(subjects):

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)


Python enumerate for loop

Another example

Python gets index in for cycle.

my_list = [0, 1, 2, 3, 4]

for idx, val in enumerate(my_list):
    print('{0}: {1}'.format(idx, val))


0: 0
1: 1
2: 2
3: 3
4: 4

Do comment if you have any doubts and suggestions on this Pytho enumerate topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.