How to access the index in a for loop in Python
Find out how to access the index in for loops in Python.
Find out how to access the index in a for loop in Python.
#more
1) Use enumerate()
¶
This can be done with the enumerate function:
my_list = ["apple", "banana", "cherry"]
for index, item in enumerate(my_list):
print(index, item)
0 apple
1 banana
2 cherry
enumerate(iterable, start=0)
¶
Iterating with enumerate
returns a tuple containing the current index and the current item for each iteration. Notice that if we use a different value for the optional start argument, the iteration over the items still starts at the first item, but the start index starts at the given value:
my_list = ["apple", "banana", "cherry"]
for index, item in enumerate(my_list, start=1):
print(index, item)
1 apple
2 banana
3 cherry
2) Use range(len(my_list))
¶
As an alternative you could also iterate over the indices using range(len(your_list))
. This works too, however, the first option using enumerate
is much better and considered to be more pythonic.
my_list = ["apple", "banana", "cherry"]
for index in range(len(my_list)):
print(index, my_list[index])
0 apple
1 banana
2 cherry
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*