Access index and value in for loop – Python

How to access index and value in for loop – Python?

This tutorial guides you on how to access index and value in for loop In Python using built-in functions like enumerate(), range() functions and also using while loop.

Access index and value in for loop – Python

Access index and value in for loop – PythonThere are multiple ways using which you can access loop index in Python. The following are some examples.

using enumerate()

The enumerate built-in option is the best approach to access index and value in for loops. This option is available in both Python 2 and 3.

Here is a sample program, which enumerates the list of integers and prints the index and value of each item in the list in for loop.

For example,

Β 

numbers = [4, 6, 10, 24, 28, 30]

for indx, val in enumerate (numbers):
    print('index is {}'.format(indx), ', value is {}'.format(val))

Output

index is 0 , value is 4
index is 1 , value is 6
index is 2 , value is 10
index is 3 , value is 24
index is 4 , value is 28
index is 5 , value is 30

Another approach using for loop

In this approach, you would use Python’s for loop itself to find the loop index as shown below.

numbers = [4, 6, 10, 24, 28, 30]

indx=0
for item in numbers:  
    print('index is {}'.format(indx), ', value is {}'.format(item))
    indx = indx + 1

Output

index is 0 , value is 4
index is 1 , value is 6
index is 2 , value is 10
index is 3 , value is 24
index is 4 , value is 28
index is 5 , value is 30

range() function in for loop

There is another way that you can access loop index by using range function in for loop as shown in the example below.

For example,

for indx in range(len(numbers)):
    print('index is {}'.format(indx), ', value is {}'.format(numbers[indx]))

Output

index is 0 , value is 4
index is 1 , value is 6
index is 2 , value is 10
index is 3 , value is 24
index is 4 , value is 28
index is 5 , value is 30

while loop to access loop index

Also, you can use while loop to access the loop index in the following way.

For example,

indx = 0
while indx < len(numbers):
    print('index is {}'.format(indx), ', value is {}'.format(numbers[indx]))
    indx = indx + 1

Output

index is 0 , value is 4
index is 1 , value is 6
index is 2 , value is 10
index is 3 , value is 24
index is 4 , value is 28
index is 5 , value is 30

That’s it. You had learnt how to access index and value in for loop using enumerate(), range() functions and also using while loop.

Hope it helped πŸ™‚

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments