Chrome Extension

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])
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Output
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)
Was this helpful?
0 Comments