/  Technology   /  Accessing the index in ‘for’ loops?

Accessing the index in ‘for’ loops?

Accessing the index in ‘for’ loops?

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

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.

 

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= ‘ ’ 

Using list comprehension:

Refer to this article for a better understanding of this code.

https://www.i2tutorials.com/list-comprehensions/

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.

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