/  Technology   /  How to access the index in ‘for’ loops in Python?
for loop accessing

How to access the index in ‘for’ loops in Python?

 

One of the simplest ways to access indices of elements in a sequence in for loops is by traversing through the length of the sequence using an iterator, increasing it by one and accessing the element at that particular sequence.

 

Consider the below list

list= [1,3,5,7,9]

Example:

list= [1,3,5,7,9]

for index in range(len(list)):
   print("Index: "+str(index)+ " , " "Value: "+str(list[index])

Output:

acessing

 

Here, index is the iterable we traverse through the list using the len() function, and the range() function starts from the index 0 to the length-1 index in the list. Upon reaching each index, we print its index and value.

 

Using enumerate():

This is one of the most efficient methods. The enumerate() function returns both the indices and values of the sequence unlike range(). Here in the for loop two iterators are used, one to iterate through the indices and the other through the values.

Example:

list= [1,3,5,7,9]

for index, value in enumerate(list):
   print("Index: "+str(index)+ " , " "Value: "+str(list[index])

Output:

 

We considered the same list named ‘list’ for the example code below. index, value are the iterators used. Using this method we can start the iteration from any index and not necessarily from 0, by passing another argument to the enumerate() function, start= ‘ ’ 

Example:

enumerate(list, start=1)

Output:

Using list comprehension:

Refer to this article list-comprehensions for a better understanding of this code.

Example:

list= [1,3,5,7,9]

print([[i, list[i]] for i in range(len(list))]

Output:

Here, we printed it in the form of a nested list where the first element in every sublist is the index and the second element in the sublist is the corresponding element.

 

Using zip():

The zip() function maps the similar index elements from two different sequences and returns them as a single entity.

Example:

list= [1,3,5,7,9]
for index, value in zip(range(len(list)), list):
   print((index,value))

Output:

In the above code, the first argument passed to the zip() function is a sequence of numbers in the range from 0 to len(list) and the second parameter is the list ‘list’. The zip() function paired up each index with its corresponding value and printed them in the form of tuples.

 

Leave a comment