Access the Index and Value using Python ‘For’ Loop
Last Updated :
06 Feb, 2024
In this article, we will get to know how to access an index value in a for loop in Python. There are many ways to access an index value in a for loop in Python but we will be studying mainly four of them using a for loop. Python programming language supports the different types of loops, the loops can be executed in different ways.
Access Index Value in a For Loop in Python
Below are some of the examples by which we can access the index value in Python:
- Using range() function
- Using enumerate() function
- Using zip() function
- Using itertools
Python Access Index & Value Using range() Function
In this method, we are using the range() function to generate indices and access values in a list by their position.
Python3
fruits = [ 'apple' , 'banana' , 'orange' ]
print ( "Indices and Index value :" )
for i in range ( len (fruits)):
print (f "Index: {i}, Value: {fruits[i]}" )
|
Output
Indices and Index value :
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange
Access Index and Value Using enumerate() in Python
In this method, we are using enumerate() in for loops to get the index value over the given range.
Python3
fruits = [ 'apple' , 'banana' , 'orange' ]
print ( "Indices and values in list:" )
for i,fruit in enumerate (fruits):
print (f "Index: {i}, value: {fruit}" )
|
Output
Indices and values in list:
Index: 0, value: apple
Index: 1, value: banana
Index: 2, value: orange
Python Access Index Value Using zip()
The zip() method in Python is used to zip the index and values at a time, we have to pass two lists one list is of index elements and another list is of values.
Python3
indexlist = [ 0 , 1 , 2 , 3 ]
fruits = [ 'apple' , 'banana' , 'orange' ]
print ( "index and values in list:" )
for index, value in zip (indexlist, fruits):
print (index, value)
|
Output
index and values in list:
0 apple
1 banana
2 orange
Access Index with Value Using itertools in Python
We can also use count from itertools along with zip() to achieve a similar effect. In this example, we have used itertools to access the index value in a for loop.
Python3
from itertools import count
fruits = [ 'apple' , 'banana' , 'orange' ]
index_counter = count()
for i, fruit in zip (index_counter, fruits):
print (f "Index: {i}, Value: {fruit}" )
|
Output
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange
Share your thoughts in the comments
Please Login to comment...