How to access the for loop index in Python

January 9, 2022

How to access the for loop index in Python

In this article, you’ll learn how to access the for loop index in Python, which is when we need to check  what step the iteration is set at.

access the for loop index in Python cover

Hey you all programmers, okay? Let’s learn more about Python!

The loop is the iteration you can do through an array, for example

Sometimes, in addition to accessing the values of a list, we want to know the index value, that is, what is the number of the iteration being executed

Here’s how to do this in Python:

items = [1,2,3,4,5]

for index, item in enumerate(items):
 print(index, item)

We need to use the enumerate function on the list of items we want to retrieve the index

And then, in addition to passing the item in the for, we need an argument that will serve as an index renderer, in this case index

See the output:

0 1
1 2
2 3
3 4
4 5

Note that index starts at 0 in Python, this happens in most languages.

So if we want to access the second element of a list, we must put list[1] instead of list[2]


In this article we learned how to access the for loop index in Python

We need to use a function called enumerate in our list of items when executing the for

And besides the item as a parameter of the for, we need to pass one to the index

That in the code example of this article, we use index

It is normal to call this parameter i and idx

Want to learn more about Python? Click here!

Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x