Get the index of the list inside python for loop

You can use enumerate() method in python to get the index inside for loop.

fruits_list = ["Apple", "Orange", "Banana", "Pineapple"]

#using enumerate() method
for index, value in enumerate(fruits_list):
    print(index, value)

#using range() method
for index in range(len(fruits_list)):
    print(index, fruits_list[index])
0 Apple
1 Orange
2 Banana
3 Pineapple

In the code snippet, we have a list named fruits_list and we are iterating it using for loop. If we want to access the iteration index inside for loop, we are using enumerate() function for that. 

Start index from another number in place of 0

You can define your index to start from another number in place of 0. you just need to pass the start parameter value inside enumerate() method. Below is the code example for that.

fruits_list = ["Apple", "Orange", "Banana", "Pineapple"]

for index, value in enumerate(fruits_list, start=10):
    print(index, value)
my_list = ["Math", "Physics", "Chemistry"]

for index in range(len(my_list)):
# Output:
# Math
# Physics
# Chemistry
We are using range() and len() method here. The len() method takes the list as a parameter and returns the length of the list. The range() function takes a number and makes the loop run N times where N is the length of the list.
Was this helpful?