How to access the index in ‘for’ loops
- tinyytopic.com
- 0
- on Mar 23, 2023
In Python, you can access the index of an element in a sequence when iterating through it using a for
loop by using the built-in function enumerate()
. Here’s an example:
fruits = ['apple', 'banana', 'cherry'] for index, fruit in enumerate(fruits): print(index, fruit)
The output of the code execution is below:
0 apple
1 banana
2 cherry
In the above example, enumerate()
is used to iterate over the fruits
list and return a tuple containing the index and the value of each element. The for
loop then unpacks the tuple into index
and fruit
variables and prints them out.
Note that the index starts from 0 by default, but you can specify a different starting value by passing a second argument to enumerate()
. For example:
fruits = ['apple', 'banana', 'cherry'] for index, fruit in enumerate(fruits, start=1): print(index, fruit)
The output of the code execution is below:
1 apple
2 banana
3 cherry