Post Image

Python Maintain Index in a For Loop

When iterating over lists it is often useful to keep some sort of an index or count of what loop you're on. In this post I will demonstrate how to do that in Python using a built-in function of the language.

 

Incorrect Way

A way that will work but is not recommended is declaring an index variable and at the end of the for loop, incrementing that variable.

my_list = ['one', 'two', 'three', 'four', 'five']

idx = 0
for element in my_list:
    print(idx)
    # do some code here
    idx += 1

Execution of that code will look like the output below.

$ example.py
0
1
2
3
4
$

 

While this works it is not recommended as Python provides a function within the language that accomplishes this which reduces the amount of code you need to write and maintain, which leads to less errors overall.

 

Using Enumerate

The built-in function "enumerate" is what does this for you. Taking a look at the code below, I modified the example above to use it versus keeping our counter variable.

my_list = ['one', 'two', 'three', 'four', 'five']

for idx, element in enumerate(my_list):
    print(idx)
    # do some code here

And running it, you can see we get the same output as before.

$ example.py
0
1
2
3
4
$

In addition, if you want you can provide a "start" argument to enumerate to set the number you wish to start on if you don't want to start from zero.

for idx, element in enumerate(my_list, start=1):

 

Enumerate Implementation

The enumerate function is implemented under the hood in C, however for an exercise I will be showing you an example in Python. To be clear this is not the exact code how it is implemented but to understand how to do a Python implementation of something like this I think this is a valuable exercise.

def enumerate(iterable, start=0):
    for element in iterable:
        yield start, element
        start += 1

As you can see under the hood in this implementation, we still have a counter variable that we increment on each run of the loop, however that is hidden away in the enumerate function so that when you use it in a for loop, that index is incremented and presented to the loop on each iteration. 

If enumerate did not exist in the language, a helper function in your codebase would be very useful but because it is already there, we do not need to worry about it.

 

 



Comments (0)
Leave a Comment