Find the index of the iterator of a list
Introduction
To find the index of the current value in a for loop on a list in Python, you can use the built-in enumerate()
function.
The enumerate()
function takes an iterable (such as a list) and returns an iterator of tuples. Each tuple contains the index of the current item and the item itself.
Example
Here's an example:
my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list):
print(index, value)
This code will output:
0 apple
1 banana
2 cherry
As you can see, the enumerate()
function returns the index of each item in the list along with the item itself.
So, to find the index of the current value in your for loop, you can simply use the index
variable that is returned by enumerate()
. For example:
my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list):
if value == 'banana':
print('Index of banana:', index)
This code will output:
Index of banana: 1
In this example, we're using an if statement to check if the current value is 'banana'. If it is, we're printing the index of 'banana' using the index
variable that is returned by enumerate()
.
And that's it! You now know how to find the index of the current value in a for loop on a list in Python using the enumerate()
function.