In this article, Get index of all occurrences of list items in Python. Indexing is the most powerful feature of an array, list, or continuous data structure and we will learn about Python list indexing in detail.
Approach to get index or position of an item
1. Get index of first occurrence of an item in list using list.index()
The list index() is an in-built method of list class. It is mainly used to find the index of a given element, by searching the whole list and return position/Index the first occurrence of a given element, if the list contains the duplicate element then it returns only the first occurrence(index/position).
Syntax
#list index method syntax
list.index(element,start,end)
Parameters
Parameters | Explanation |
element | This represents the element that’s the index we want to find in the list. |
start | This is an optional parameter, has a default value of 0. It represents the start index to find the element. |
end | an optional parameter, it represents the stop index to find the element, if not specify the end index it considers till the end of the list. |
Error: If the index of the element is not found in the list then it raises a ValueError:
let us understand with code example
animal_list = ['dog','cat','mouse','ant','bee','fly','spider','rat']
#item index to find
item_to_find = 'bee'
index = animal_list.index(item_to_find)
print('the index of element is =',index)
Output
the index of element is = 4
2.Get last index of an item in list Using list slicing
Here in this code snippet, we are using list slicing to get the last occurrence of the element.
animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat']
item_to_find = 'cat'
last_index = len(animal_list) - 1 - animal_list[::-1].index(item_to_find)
print('last index indexes of item "cat" =',last_index)
Output
last index indexes of item "cat" = 6
3. Get indexes of all occurrence of an item in List using list comprehension
The list index() method is used to find the first occurrence of element,but it is not enough to fulfill our requirements while doing data manipulation.Sometime We have to find index/position of all occurrence of an item in list item. By using List comprehension we can achieve this.
let us dive into code example
#program to find index of item in list
animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat']
item_to_find = 'cat'
list_all_indexes = [item for item in range(len(animal_list)) if animal_list[item] == item_to_find]
print('all indexes of item "cat" in list =',list_all_indexes)
Output
all indexes of item "cat" in list = [1, 3, 5, 6]
4. Get indexes of all occurrence of an item in a list Using more_itertools.locate()
The more_itertools.locate() module can be used to find the indexes of all occurrences of an item. To use this module first we have to install it, otherwise, we will get the ModuleNotFoundError: No module named ‘more_itertools’.
We pass the lambda function to locate() method, this lambda function contains the logic to match our search criteria. We pass the full list and the lambda function to locate function then locate function returns the index numbers for which our lambda functions held true. This is how we get the multiple indexes if the element is found at multiple indexes.
Now let us see this in practice with our example.
from more_itertools import locate
animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat']
item_to_find = 'cat'
list_of_all_indexes = list(locate(animal_list, lambda item: item == item_to_find))
print('all indexes of item "cat" in list =',list_of_all_indexes)
Output
all indexes of item "cat" in list = [1, 3, 5, 6]
5. Get indexes of all occurrence of an item in the list Using enumerate() function
The enumerate() function can be used to get indexes of all occurrences of an item. The enumerate() function adds a counter to an iterable object and returns it.
Syntax
enumerate(iterable_object,start)
Parameters
Name | Explanation |
iterable_object | It represents the iterable object [list, tuple, string, dictionary], or object that support iteration |
start | It represents the counter number from which enumerate() counter start, default it starts at 0. |
animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat']
list_of_indexes = []
item_to_find = 'cat'
for (index, item) in enumerate(animal_list):
if item == item_to_find:
list_of_indexes.append(index)
print('all indexes of item "cat" in list =',list_of_indexes)
Output
all indexes of item "cat" in list = [1, 3, 5, 6]
6. Get indexes of all occurrence of an item in the list Using NumPy
Here in this code example, we are using the NumPy module to find indexes of all occurrence of an item in list.We are using Numpy provided where() function that return the item which fulfill the given conditions.
Let is understand with example.
import numpy as np
animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat']
item_to_find = 'cat'
np_array = np.array(animal_list)
list_of_indexes = np.where(np_array == item_to_find)[0]
print('all indexes of item "cat" in list =',list_of_indexes)
Output
all indexes of item "cat" in list = [1 3 5 6]
7. Get indexes of all occurrence of an item in the list Using filter()
Python filter() method run as a function on all elements of an iterable object to filter the object and returns those elements as iterator which fulfill the condition in function. We can better understand with below code snippet.
animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat']
item_to_find = 'cat'
list_of_indexes = list(filter(lambda item: animal_list[item] == item_to_find, range(len(animal_list))))
print('all indexes of item "cat" in list =',list_of_indexes)
Output
all indexes of item "cat" in list = [1, 3, 5, 6]
8. Get indexes of all occurrences of an item in the list Using while loop and list.index()
As we have already seen the list.index() find the index of the first occurrence of an item. But by using the loop we can find all the occurrence of element and append in the result list. We are looping from the first element to the end of the list.
animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat']
item_to_find = 'cat'
list_of_indexes = []
item_index = 0
while True:
try:
item_index = animal_list.index(item_to_find,item_index+1)
list_of_indexes.append(item_index)
except ValueError:
break
print('all indexes of item "cat" in list =',list_of_indexes)
Output
all indexes of item "cat" in list = [1, 3, 5, 6]
Conclusion
We hope we will use these ways to get the index or position of an element in Python list.