Software developers often employ different kinds of loops to iterate over data. While doing so, they sometimes need to get the index value of loop. There are several ways to access index value in for loop in Python. We will learn 8 different ways to retrieve the index value in a Python loop.
How to Access Index Value in for Loop in Python
Let us look at the different ways to access index value in for loop in Python. Let us say you have the following loop in Python.
data = ['a','b','c','d','e']
Let us see different ways to get the index value while looping through the above list.
1. Using range() function
Range() is a useful Python function that allows you to obtain a sequence of consecutive numbers starting from zero, until the specific number. We can loop through its result to obtain the index value for each item in the original list/array.
Here is the code to demonstrate it.
>>> for i in range(len(data)):
print(i, data[i])
Here is the output.
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
In the above code, len() function returns the length of data list. Range() function returns a list of 5 consecutive numbers starting with 0. We loop through this list and in each iteration, use the list item as index to obtain the original data list’s element. In each iteration, we print the index and value.
Please note, you can use this method on any iterable data, including strings. Here is an example.
data = "Hello"
>>> for i in range(len(data)):
print(i, data[i])
(0, 'H')
(1, 'e')
(2, 'l')
(3, 'l')
(4, 'o')
This is a very simple and intuitive solution to easily access index values in loops. They can also be used in while loops.
2. Using enumerate() function
Enumerate() is a useful Python function that adds a counter variable to an iterator, iterates through the iterable and returns pairs of index & values. It is useful to easily get index, value pairs from iterables.
data = ['a','b','c','d','e']
>>> for i in enumerate(data):
print(i)
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
In the above code, enumerate() functions adds an index counter to the data list. Then in each iteration, it returns the pairs of index & corresponding value from the list. You can also separately pick index and value from enumerate as shown below.
>>> for index,value in enumerate(data):
print(index,value)
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
The above approach allows you to easily access only the index or value as per your requirement, instead of working the enumerate tuple(index, value).
By default, the starting index value of enumerate() function is zero. If you want, you can start it from another number by passing start option, as shown below. Here is an example to start enumerate() index from 2.
>>> for i,v in enumerate(data, start=2):
print(i,v)
(2, 'a')
(3, 'b')
(4, 'c')
(5, 'd')
(6, 'e')
In the above code, the starting counter index is 2.
Using enumerate() is generally favored by Python developers since it is very pythonic in nature. It is very fast, even if it appears as an overhead in the above code. So it can be used for large lists also.
3. Using List Comprehension
List comprehension allows you to create a new list based on an existing list. This can be used to create a list of indexes for a given list. Here is a list comprehension to get a list of indexes based on data list.
>>> print([i for i in range(len(data))])
[0, 1, 2, 3, 4]
We can use the elements of above list to get list elements from original list.
>>> print([data[i] for i in range(len(data))])
['a', 'b', 'c', 'd', 'e']
You can also access the index as well as list values at the same time. Here we fetch the index and value pairs as tuples.
>>> print([(i,data[i]) for i in range(len(data))])
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
Some software developers find it difficult to figure out how list comprehensions work since we are basically cramming all the processing in a single line. Nevertheless, if you are comfortable with list comprehensions then they are definitely useful in this case.
4. Using zip() function
Zip() function allows you to combine 2 lists and iterate over both of them at once. For our purpose, we will use zip() function to combine and iterate over two lists – one with the indexes and the other with the values.
data = ['a','b','c','d','e']
indexes = [i for i in range(len(data))]
>>> for index, value in zip(indexes, data):
print(index, value)
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
Zip() function is super fast and works great even for large lists. However, you need to generate an additional list of indexes for this method. Otherwise, it is quite scalable, just like using enumerate().
5. Using counter variable
If you are looking for an easy to understand solution, then this is one of the simplest ways to easily access index variable in loop. Just set a counter variable to initial index value, that is, zero. In each iteration, increment the counter by 1.
>>> for i in data:
print(counter, i)
counter+=1
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
Even beginner developers can easily use this solution.
6. Using yield statement
Yield statement is used to create generator function. It returns an iterator to a generator object. Every time, you access this iterator, it will return the next value in the sequence, without storing the entire sequence in memory. This is a useful method if you have a very large list that occupies lot of memory space.
def create_gen():
data = ['a','b','c','d','e']
for (j, k) in enumerate(data):
yield (j, k)
generator = create_gen()
for i in generator:
print(i)
In the above code, we create a generator function that loops through a list using enumerat() function and returns an iterator to the generator object. We loop this generator object to get index-value pairs.
7. Using lambda
Lambda are small, anonymous Python functions that accept one or more arguments but contain only a single expression. They cannot have multiple statements like a full fledged function. They are useful for writing compact code. Here is an example to access index values in a for loop using lambda functions.
>>> data = ['a','b','c','d','e']
>>> x = lambda u:[(i, data[i]) for i in range(0, u)]
>>> print(x(5))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
8. Using Pandas
Sometimes, your list may have unique indexes that cannot be accessed using enumerate() function. For example, if you have created Pandas series objects, then this will be the case. Let us say you have the following Series object with index as shown.
import pandas as pd
xs = pd.Series([18, 13, 15])
xs.index = ['A123002', 'A123004', 'A123005']
If you use enumerate() function, this is what you get.
for id, x in enumerate(xs):
print("item #{} = {}".format(id, x))
# item #0 = 18
# item #1 = 13
# item #2 = 15
Instead, you can use items() function available for each pandas series object.
for id, x in xs.items():
print("item #{} = {}".format(id, x))
# item #A123002 = 8
# item #A123004 = 23
# item #A123005 = 45
If you are using Pandas library or need to work with Series objects then you can use this method.
Conclusion
In this article, we have learnt several different ways to access loop index in Python. You can use any of them as per your requirement. Even though we have demonstrated most of the solutions using for loop, you can also use it for other loop statements such as while loops. Among them, using enumerate() is one of the fastest ways to access indexes, and works well on large lists also.
FAQ
1. Do these solutions work for while loops?
Yes. They work for all kinds of loop statements in Python such as for loop, while loop, do…while, etc.
2. Do these methods also work for strings and other iterables?
Yes. They work on all iterables such as list, strings, etc. They also work on list of numbers, strings, tuples, and other data types.
3. Which is the most efficient of these solutions?
Among all the solutions provided above, using enumerate() is considered as the most efficient as well as most pythonic way of accessing index values.
Also read:
How to Create Directory With Missing Parent Directory
Does Python Have Ternary Operator?
How to Read Large File in Python?
Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.