Often software developers need to determine the index of a given element in Python lists. This is mainly required if you have a large list and want to search for one or more occurrences of a specific element. There are several simple ways to solve this problem using Python. In this article, we will learn how to find index of a given item in list in Python.
How to Find Index of Given Item in List in Python
Before we proceed further, it is important to understand three critical use cases, when it comes to searching for an item in a list. First is when there is a single occurrence of a given item. Second, when there are multiple occurrences of given item. Third, when there is no occurrence of given item. In each of the following solutions, we will look at these use cases.
1. Using index() function
Every list supports an index() function that returns the index of the first occurrence of an element in the list. The index value starts from 0. If there are multiple occurrences of an item, it will still return the index of only the first item. If there are no occurrences, then it will throw a ValueError exception.
Here is its syntax.
list.index(x[, start[, end]])
In the above function, x is the item whose index you are looking for in the list. Start and end are optional arguments, to limit your search to a specific sublist of the given list. This is useful if you are dealing large lists, or you are sure to find an element in a specific sub-section of the given list.
Let us say you have the following list
a = [1, 2, 3, 4, 5]
Here is the command to get index of item value=3 in the above list.
print(a.index(3)) # output is 2
Let us say you try to get the index of item=0 which does not exist in the list.
print(a.index(0))
You will get the following error message.
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
ValueError: 0 is not in list
To avoid this problem, it is better to wrap the index() function in a try-except block.
try:
print(a.index(0))
except ValueError:
print('value not found')
Now when you run the above code, you will get the message ‘value not found’ instead of the error.
Let us say you have the following list with multiple occurrences of item=3.
a = [1, 2, 3, 4, 5, 3]
If you use index() function, it will return only the index of first occurrence.
print(a.index(3)) # output is 2
In this case, you need to use the next solution using enumerate() function.
2. Using enumerate() function
Enumerate() function iterates over an iterable and automatically assigns an index for each item, which can then be retrieved. This makes it easy to access list items.
There are two ways to use enumerate() function to get index of list item, whether there is single or multiple occurrence. Let us say you have the following list with 2 occurrences of item=3.
a = [1, 2, 3, 4, 5, 3]
Here is the code to get indexes of item=3.
print([i for i, e in enumerate(a) if e == 3])
Here is the output.
[2, 5]
In the above code, we use a list comprehension, where we get a list of tuples as a result of enumerate() function. Each tuple consists of index, value combination. In our list comprehension, we loop through this list and in each iteration check if the value is 3. If so, we save the index in final list.
The above solution works for most lists. However, if your list is really large and there are too many occurrences (say, millions) then the resultant list will occupy a lot of space. To overcome this problem, you can use a generator comprehension that returns an iterable object.
g = (i for i, e in enumerate(a) if e == 3)
In the above code, g is simply an iterator to a generator object and it does not occupy much space. You can access the individual indexes using next() function.
>>> next(g)
2
>>> next(g)
5
In both these cases, if there is no occurrence of the item, then it will return an empty list, instead of throwing an error. So this method is quite comprehensive since it deals with no occurrence, single occurrence as well as multiple occurrences of an item.
3. Using itertools
Itertools is a popular Python library that provides tons of useful functions to work with iterable data such as lists, sets, etc. Among them, you can use izip() and count() functions to easily get indexes of one or more occurrences of an item in a list.
a = [1, 2, 3, 4, 5, 3]
from itertools import izip, count
print([i for i, j in izip(count(), a) if j == 3])
Output is [2, 5].
Using itertools is faster than using enumerate() especially for larger lists, since it works using iterators and generator objects, which are time as well as memory efficient.
4. Using range() function
You can also use a simple range() function to get a list of indexes for a given list item.
indexes = [i for i in range(len(a)) if a[i] == 3]
print(indexes)
In the above code, we use a list comprehension. In it, we use len() function to get the length of given list a. Then we use range() function to first get a list of indexes with length equal to that of given list. We iterate through this list of indexes and in each iteration, we check if the value of that index is equal to given item. If so, we store it in the result list.
5. Using numpy
Numpy is a popular Python module that allows you to perform various operations on numbers. It is commonly used for its computational power, by scientists, data analysts and businesses. You can use its where() function to determine the index of a given item in a list. Here is an example to illustrate it.
import numpy as np
a = [1, 2, 3, 4, 5, 3]
item = 3
np_array = np.array(a)
indexes = np.where(np_array==item)
print(indexes)
Here is the output.
(array([2, 5]),)
In the above code, we first import Numpy library. Then we create a Numpy array from list a. Then we pass this array in where() function with the condition checking if item=3 exists in it. We store all result indexes in a result array.
This is a very useful solution for large lists because Numpy arrays are more efficient than Python lists.
6. Different data types
So far, we have seen examples where the original list contains only numbers and the item whose index we need, is also a number. What if the original list contains strings or dictionaries? All the above methods work for all those data types also. Let us say you have a list of strings, and you need to look for a string as shown.
a = ['hello', 'good', 'morning']
item = 'good'
Here are the above ways to get the index of list item using index() function.
print(a.index(item)) # output is 1
Here we use enumerate() function along with list comprehension, exactly as we did in solution #2 above.
print([i for i, e in enumerate(a) if e == item]) # output is [1]
Using izip() and count() function in itertools, we can get index of list item.
from itertools import izip, count
print([i for i, j in izip(count(), a) if j == item]) # output is [1]
You can also do the same thing using range() function.
indexes = [i for i in range(len(a)) if a[i] == item]
print(indexes) # output is [1]
Here is how to do it using Numpy arrays.
import numpy as np
np_array = np.array(a)
indexes = np.where(np_array==item)
print(indexes) # output is (array([1]),)
You can also apply all the above solutions where your original list contains dict items and you need to get the index of another dict.
a = [{1:1,2:2},{3:3,4:4}]
item = {1:1,2:2}
Here is an example to get index of list item using index() function.
print(a.index(item)) # output is 0
Here is a demonstration of how enumerate() function can also be used to get index of dict in a list of dict.
print([i for i, e in enumerate(a) if e == item]) # output is [0]
As mentioned earlier, you can also use itertools for this purpose.
from itertools import izip, count
print([i for i, j in izip(count(), a) if j == item]) # output is [0]
You can also use range() function to get index of a dict in a list of dict.
indexes = [i for i in range(len(a)) if a[i] == item]
print(indexes) # output is [0]
Lastly, here is how to do it using Numpy library.
import numpy as np
np_array = np.array(a)
indexes = np.where(np_array==item)
print(indexes) # output is (array([0]),)
Conclusion
In this article, we have learnt how to find index of an item in Python list. They work with lists containing all sorts of data items – numbers, strings, dictionaries, etc. We have learnt how to find index using index() function. We also learnt how to use enumerate() and itertools along with list comprehensions for the same purpose. These methods work for single, multiple and no occurrence of item in list. We also looked at how to fix this problem using Numpy tools.
If you are working with small lists where you know that your item exists, use index() function. If you are not sure about the presence of the item in list, or if there are multiple occurrences, use enumerate() function. If you are working with large lists, use itertools or Numpy library.
FAQ
1. Do these solutions work on lists with strings, numbers, dictionary, etc.?
Yes. They work with lists that contain numbers and strings.
2. Which solution to use for large lists?
If your list is large, then use enumerate() function with generator comprehension, or use itertools function izip() with count(). They both use iterator to a generator object, which is memory efficient.
Also read:
How to Flatten List of Lists in Python
How to Access Index Value in For Loop
How to Create Directory with Missing Parent Directory
Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.