The for loop in Python allows the user to iterate through a variable that is
iterable
, such as a list. In Python the syntax for the loop is simply:
for x in my_list:
and you’re off looping through each element in
my_list
. But how do you access the index number of the element?
In other programming languages, such as JavaScript, looping involves just the index number:
for (var i = 0; i < my_list.length; i += 1) {
var elem = my_list[i]
}
But what would be Python’s equivalent?
In Python to obtain the index number you need to wrap your list in the
enumerate
()
function which returns an enumerate object. In essence this function translates something like a list into a list of tuples with the first item in the tuple representing the index number.
Here’s what it look like upon inspection:
>>> my_list = ['a', 'b', 'c']
>>> e_list = list(enumerate(my_list))
>>> print(e_list)
[(0, 'a'), (1, 'b'), (2, 'c')]
Notice how each element is now contained within a tuple with the first element representing the index number, and the second element within each element representing the actual list in the original list.
Get Index Number In For Loop
Therefore, to obtain the index number inside the for loop you can declare a variable according to the placement of values in the enumerated tuple. As the index number is first in the tuple you would declare your index variable first in the for loop followed by the variable referencing the element, like so:
>>> my_list = ['a', 'b', 'c']
>>> for idx, elem in enumerate(my_list):
... print(idx, elem)
...
0 a
1 b
2 c
Notice how the reference of each variable in the order of the enumerated tuple produces the desired result.
This is how you can use two variables in a for loop: one that captures the index number and the other that captures the element in the list being parsed through.
The equivalent of using the enumerate on a for loop would be to declare an index variable outside the for loop and to iterate that variable each time, something like this:
>>> my_list = ['a', 'b', 'c']
>>> idx = 0
>>> for elem in my_list:
... print(idx, elem)
... idx += 1
0 a
1 b
2 c
The code contains more lines than the enumerate example, but demonstrates how you can loop and increment a variable in Python .
Summary
To use two variables in a for loop in Python use the built-in
enumerate()
function which provides access to an index number for each element. The order of the two variables used this way in a for loop is to declare the index variable
first
followed by the variable containing each element, for example:
for idx, elem in my_list: