Often times when iterating over a list or other iterable in a for loop you will need to keep track of what element you are on. If you have never been exposed to the enumerate() builtin function you may solve that problem by creating a counter variable and incrementing that counter at the end of your loop. Below is an example of that.

my_list = ['first', 'second', 'third', 'fourth']
counter = 0

for n in my_list:
    # Do stuff here
    counter += 1

In this simple example we can see how we can access our counter variable within the loop to keep track of the index of the element we are working on. While this work there is a better and more clean way to achieve this functionality which will prove to be more readable in a more complex for loop.

 

Using enumerate

The enumerate() function is built into the Python standard library so there are no additional dependancies you will need to install to do this. What enumerate does is gives you a counter variable within a for loop directly so we can keep track of the element we are working on within the for loop. If you dont understand below is example code showing you how to do that.

my_list ['first', 'second', 'third', 'fourth']

for index, element in enumerate(my_list):
    # do stuff
    print('Working on element {}'.format(element))
    print('Our index is {}'.format(index))

 

Looking at the code sample above, we have eliminated the need to explicitly declare our counter variable outside of our for loop, and we no longer have to manually increment our counter variable, this is done automatically for us via enumerate()

 

While both examples do work, using enumerate is more pythonic and should be used in place of the first example. I hope this article was able to help you!