Given a list, the task is to write a Python Program to get the indices of all occurrences of an element in a list.
Find index of all occurrences of an item using loop
This method to get the indices of all occurrences of an element in a list. Here we use a for-loop to iterate through each element in the original list.
Python3
my_list
=
[
1
,
2
,
3
,
1
,
5
,
4
]
list_size
=
len
(my_list)
for
itr
in
range
(list_size):
if
(my_list[itr]
=
=
1
):
print
(itr)
Time Complexity: O(n)
Space Complexity: O(1)
Find index of all occurrences of an item using list comprehension
This is a simple method to get the indices of all occurrences of an element in a list using list comprehension. Here we use a list comprehension to iterate through each element in the original list.
Python3
my_list
=
[
1
,
2
,
3
,
1
,
5
,
4
]
item
=
1
indices
=
[i
for
i
in
range
(
len
(my_list))
if
my_list[i]
=
=
item]
print
(indices)
Time Complexity: O(n)
Auxiliary Space: O(1)
Find index of all occurrences of an item using enumerate() function
Instead of using for-loop we can use enumerate function. This function adds a counter to an iterable and returns the enumerated object. For this, we will create a list and then we will create enumerate function to get indices of all occurrences of an element in a list
Python3
my_list
=
[
1
,
2
,
3
,
1
,
5
,
4
]
indices
=
[ind
for
ind, ele
in
enumerate
(my_list)
if
ele
=
=
1
]
print
(indices)
Time Complexity: O(n)
Space Complexity: O(n)
Find index of all occurrences of an item using itertools module
An itertools module is a memory-efficient tool that is useful by itself or in combination, so for this, we will use count() methods from this module which will return an iterator of evenly spaced values from the start value. For this, we will create a list, and then using comprehension with zip() we will get indices of all occurrences of an element in a list.
Python3
from
itertools
import
count
my_list
=
[
1
,
2
,
3
,
1
,
5
,
4
]
indices
=
[ind
for
ind,
ele
in
zip
(count(),
my_list)
if
ele
=
=
1
]
print
(indices)
Get the indices of all occurrences of an element using Numpy library
NumPy is a general-purpose array-processing package, it provides convenient ways to use arrays in Python. For this, we will create an array using numpy.array() and then get all the indices of elements in an input array when the condition is satisfied using numpy.where() methods.
Python3
import
numpy
my_list
=
numpy.array([
1
,
2
,
3
,
1
,
5
,
4
])
indices
=
numpy.where(my_list
=
=
1
)[
0
]
print
(indices)
Output :
[0, 3]
Get the indices of all occurrences of an element using the Python Dictionary
Python3
indices
=
{}
my_list
=
[
1
,
2
,
3
,
1
,
5
,
4
]
for
i
in
range
(
len
(my_list)):
if
my_list[i]
in
indices.keys():
indices[my_list[i]].append(i)
else
:
indices[my_list[i]]
=
[i]
print
(indices[
1
])
Get the indices of all occurrences of an element using the Panda library
Step-by-step algorithm:
- Import the pandas library
- Initialize the list “my_list” and the item whose indices are to be found
- Create a pandas dataframe “df” with a column “col” containing the elements of the list
- Filter the dataframe rows based on the value of the “col” column matching the given item
- Get the indices of the filtered rows
- Convert the pandas index object to a list
- Print the list of indices
Python3
import
pandas as pd
my_list
=
[
1
,
2
,
3
,
1
,
5
,
4
]
item
=
1
df
=
pd.DataFrame({
'col'
: my_list})
indices
=
df.index[df[
'col'
]
=
=
item].tolist()
print
(indices)
Time complexity: O(n), where n is the number of elements in the input list.
This is because creating the pandas data frame takes O(n) time, and filtering the data frame takes O(n) time in the worst case.
Auxiliary Space: O(n), where n is the number of elements in the input list.
This is because creating the pandas data frame requires O(n) space to store the elements of the list.
Last Updated :
24 Mar, 2023
Like Article
Save Article
Create a generator
Generators are fast and use a tiny memory footprint. They give you flexibility in how you use the result.
def indices(iter, val):
"""Generator: Returns all indices of val in iter
Raises a ValueError if no val does not occur in iter
Passes on the AttributeError if iter does not have an index method (e.g. is a set)
"""
i = -1
NotFound = False
while not NotFound:
try:
i = iter.index(val, i+1)
except ValueError:
NotFound = True
else:
yield i
if i == -1:
raise ValueError("No occurrences of {v} in {i}".format(v = val, i = iter))
The above code can be use to create a list of the indices: list(indices(input,value))
; use them as dictionary keys: dict(indices(input,value))
; sum them: sum(indices(input,value))
; in a for loop for index_ in indices(input,value):
; …etc… without creating an interim list/tuple or similar.
In a for loop you will get your next index back when you call for it, without waiting for all the others to be calculated first. That means: if you break out of the loop for some reason you save the time needed to find indices you never needed.
How it works
- Call
.index
on the inputiter
to find the next occurrence of
val
- Use the second parameter to
.index
to start at the point
after the last found occurrence - Yield the index
- Repeat until
index
raises aValueError
Alternative versions
I tried four different versions for flow control; two EAFP (using try - except
) and two TBYL (with a logical test in the while
statement):
- “WhileTrueBreak”:
while True:
…except ValueError: break
. Surprisingly, this was usually a touch slower than option 2 and (IMV) less readable - “WhileErrFalse”: Using a bool variable
err
to identify when aValueError
is raised. This is generally the fastest and more readable than 1 - “RemainingSlice”: Check whether val is in the remaining part of the input using slicing:
while val in iter[i:]
. Unsurprisingly, this does not scale well - “LastOccurrence”: Check first where the last occurrence is, keep going
while i < last
The overall performance differences between 1,2 and 4 are negligible, so it comes down to personal style and preference. Given that .index
uses ValueError
to let you know it didn’t find anything, rather than e.g. returning None
, an EAFP-approach seems fitting to me.
Here are the 4 code variants and results from timeit
(in milliseconds) for different lengths of input and sparsity of matches
@version("WhileTrueBreak", versions)
def indices2(iter, val):
i = -1
while True:
try:
i = iter.index(val, i+1)
except ValueError:
break
else:
yield i
@version("WhileErrFalse", versions)
def indices5(iter, val):
i = -1
err = False
while not err:
try:
i = iter.index(val, i+1)
except ValueError:
err = True
else:
yield i
@version("RemainingSlice", versions)
def indices1(iter, val):
i = 0
while val in iter[i:]:
i = iter.index(val, i)
yield i
i += 1
@version("LastOccurrence", versions)
def indices4(iter,val):
i = 0
last = len(iter) - tuple(reversed(iter)).index(val)
while i < last:
i = iter.index(val, i)
yield i
i += 1
Length: 100, Ocurrences: 4.0%
{'WhileTrueBreak': 0.0074799987487494946, 'WhileErrFalse': 0.006440002471208572, 'RemainingSlice': 0.01221001148223877, 'LastOccurrence': 0.00801000278443098}
Length: 1000, Ocurrences: 1.2%
{'WhileTrueBreak': 0.03101000329479575, 'WhileErrFalse': 0.0278000021353364, 'RemainingSlice': 0.08278000168502331, 'LastOccurrence': 0.03986000083386898}
Length: 10000, Ocurrences: 2.05%
{'WhileTrueBreak': 0.18062000162899494, 'WhileErrFalse': 0.1810499932616949, 'RemainingSlice': 2.9145700042136014, 'LastOccurrence': 0.2049500006251037}
Length: 100000, Ocurrences: 1.977%
{'WhileTrueBreak': 1.9361200043931603, 'WhileErrFalse': 1.7280600033700466, 'RemainingSlice': 254.4725100044161, 'LastOccurrence': 1.9101499929092824}
Length: 100000, Ocurrences: 9.873%
{'WhileTrueBreak': 2.832529996521771, 'WhileErrFalse': 2.9984100023284554, 'RemainingSlice': 1132.4922299943864, 'LastOccurrence': 2.6660699979402125}
Length: 100000, Ocurrences: 25.058%
{'WhileTrueBreak': 5.119729996658862, 'WhileErrFalse': 5.2082200068980455, 'RemainingSlice': 2443.0577100021765, 'LastOccurrence': 4.75954000139609}
Length: 100000, Ocurrences: 49.698%
{'WhileTrueBreak': 9.372120001353323, 'WhileErrFalse': 8.447749994229525, 'RemainingSlice': 5042.717969999649, 'LastOccurrence': 8.050809998530895}
Условие:
Создайте функцию, которая вернет индексы всех вхождений элемента в списке.
Примеры:
get_indices(["a", "a", "b", "a", "b", "a"], "a") ➞ [0, 1, 3, 5]
get_indices([1, 5, 5, 2, 7], 7) ➞ [4]
get_indices([1, 5, 5, 2, 7], 5) ➞ [1, 2]
get_indices([1, 5, 5, 2, 7], 8) ➞ []
Примечание:
- Если элемента нет в списке, то возвращаем
[]
. - Индекс списка начинается с 0.
- Без вложенных списков и сложных конструкций внутри списка.
Решение:
def get_indices(lst, el): return [i for i in range(len(lst)) if lst[i] == el]
def get_indices(lst, el): list = [] for i in range(len(lst)): if lst[i] == el: list.append(i) return list
В этом посте будет обсуждаться, как найти индекс всех вхождений элемента в списке Python.
1. Использование enumerate()
функция
Чтобы получить индекс всех вхождений элемента в список, вы можете использовать встроенную функцию enumerate(). Он был введен для решения задачи счетчика циклов и может использоваться следующим образом:
if __name__ == ‘__main__’: ints = [1, 3, 7, 5, 4, 3] item = 3 for index, elem in enumerate(ints): if elem == item: print(f“{item} is found at index {index}”) ”’ Output: 3 is found at index 1 3 is found at index 5 ”’ |
Скачать Выполнить код
Чтобы получить список всех индексов сразу, используйте понимание списка с функцией перечисления:
if __name__ == ‘__main__’: ints = [1, 3, 7, 5, 4, 3] item = 3 indexes = [i for i, j in enumerate(ints) if j == item] print(f“Item {item} is found at index {indexes}”) # результат: Item 3 is found at index [1, 5] |
Скачать Выполнить код
2. Использование range()
функция
В качестве альтернативы вы можете использовать range()
функция, чтобы получить список всех допустимых индексов, а затем сопоставить соответствующее значение, присутствующее в каждом индексе, с данным элементом.
if __name__ == ‘__main__’: ints = [1, 3, 7, 5, 4, 3] item = 3 indexes = [i for i in range(len(ints)) if ints[i] == item] print(f“Item {item} is found at index {indexes}”) # результат: Item 3 is found at index [1, 5] |
Скачать Выполнить код
Другой подход заключается в использовании count()
функционировать в itertools
, который создает итератор для эффективного цикла, чтобы возвращать равномерно распределенные значения, начиная с заданного числа. Вы можете использовать его с zip()
для добавления порядковых номеров следующим образом.
from itertools import count if __name__ == ‘__main__’: ints = [1, 3, 7, 5, 4, 3] item = 3 zipped = [(i, j) for i, j in zip(count(), ints) if j == item] print(zipped) # [(1, 3), (5, 3)] |
Скачать Выполнить код
The more-itertools
библиотека предоставляет элегантные подпрограммы для работы с итерируемыми объектами Python. Вы можете использовать more_itertools.locate функция, которая возвращает индекс каждого элемента в итерируемом объекте, для которого выполняется заданный предикат. Ниже приведен простой пример, демонстрирующий использование этой функции:
from more_itertools import locate if __name__ == ‘__main__’: ints = [1, 3, 7, 5, 4, 3] item = 3 indexes = list(locate(ints, lambda x: x == item)) print(f“Item {item} is found at index {indexes}”) # результат: Item 3 is found at index [1, 5] |
Скачать код
5. Использование NumPy
Библиотека
Наконец, если вы используете NumPy
уже и нужны все индексы, вы можете использовать numpy.where()
функция.
import numpy as np if __name__ == ‘__main__’: ints = [1, 3, 7, 5, 4, 3] item = 3 indexes = np.where(np.array(ints) == item)[0] print(f“Item {item} is found at index {indexes}”) # результат: Item 3 is found at index [1, 5] |
Это все, что касается поиска индекса всех вхождений элемента в списке в Python.
In this tutorial, you’ll learn how to use the Python list index method to find the index (or indices) of an item in a list. The method replicates the behavior of the indexOf() method in many other languages, such as JavaScript. Being able to work with Python lists is an important skill for a Pythonista of any skill level. We’ll cover how to find a single item, multiple items, and items meetings a single condition.
By the end of this tutorial, you’ll have learned:
- How the Python
list.index()
method works - How to find a single item’s index in a list
- How to find the indices of all items in a list
- How to find the indices of items matching a condition
- How to use alternative methods like list comprehensions to find the index of an item in a list
Python List Index Method Explained
The Python list.index()
method returns the index of the item specified in the list. The method will return only the first instance of that item. It will raise a ValueError
is that item is not present in the list.
Let’s take a look at the syntax of the index()
method:
# The list.index() Method Explained
list.index(
element, # The element to search for
start, # The index to start searching at
end # The index to end searching at
)
Let’s break these parameters down a little further:
element=
represents the element to be search for in the liststart=
is an optional parameter that indicates which index position to start searching fromend=
is an optional parameter that indicates which index position to search up to
The method returns the index of the given element if it exists. Keep in mind, it will only return the first index. Additionally, if an item doesn’t exist, a ValueError
will be raised.
In the next section, you’ll learn how to use the .index()
method.
Find the Index Position of an Item in a Python List
Let’s take a look at how the Python list.index()
method works. In this example, we’ll search for the index position of an item we know is in the list.
Let’s imagine we have a list of the websites we open up in the morning and we want to know at which points we opened 'datagy'
.
# Finding the index of an item in a list
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(a_list.index('datagy'))
# Returns: 0
We can see that the word 'datagy'
was in the first index position. We can see that the word 'twitter'
appears more than once in the list. In the next section, you’ll learn how to find every index position of an item.
Finding All Indices of an Item in a Python List
In the section above, you learned that the list.index()
method only returns the first index of an item in a list. In many cases, however, you’ll want to know the index positions of all items in a list that match a condition.
Unfortunately, Python doesn’t provide an easy method to do this. However, we can make use of incredibly versatile enumerate()
function and a for-loop to do this. The enumerate function iterates of an item and returns both the index position and the value.
Let’s see how we can find all the index positions of an item in a list using a for loop and the enumerate()
function:
# Finding all indices of an item in a list
def find_indices(search_list, search_item):
indices = []
for (index, item) in enumerate(search_list):
if item == search_item:
indices.append(index)
return indices
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'twitter'))
# Returns: [1, 3]
Let’s break down what we did here:
- We defined a function,
find_indices()
, that takes two arguments: the list to search and the item to find - The function instantiates an empty list to store any index position it finds
- The function then loops over the index and item in the result of the
enumerate()
function - For each item, the function evaludates if the item is equal to the search term. If it is, the index is appended to the list
- Finally, this list is returned
We can also shorten this list for a more compact version by using a Python list comprehension. Let’s see what this looks like:
# A shortened function to return all indices of an item in a list
def find_indices(search_list, search_item):
return [index for (index, item) in enumerate(search_list) if item == search_item]
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'twitter'))
# Returns: [1, 3]
One of the perks of both these functions is that when an item doesn’t exist in a list, the function will simply return an empty list, rather than raising an error.
Find the Last Index Position of an Item in a Python List
In this section, you’ll learn how to find the last index position of an item in a list. There are different ways to approach this. Depending on the size of your list, you may want to choose one approach over the other.
For smaller lists, let’s use this simpler approach:
# Finding the last index position of an item in a list
def find_last_index(search_list, search_item):
return len(search_list) - 1 - search_list[::-1].index(search_item)
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_last_index(a_list, 'twitter'))
# Returns: 3
In this approach, the function subtracts the following values:
len(search_list)
returns the length of the list1
, since indices start at0
- The
.index()
of the reversed list
There are two main problems with this approach:
- If an item doesn’t exist, an
ValueError
will be raised - The function makes a copy of the list. This can be fine for smaller lists, but for larger lists this approach may be computationally expensive.
Let’s take a look at another approach that loops over the list in reverse order. This saves the trouble of duplicating the list:
# A less simple, but more memory efficient way of finding the last index of an item
def find_last_index(search_list, search_item):
i = len(search_list) - 1
while i >= 0:
if search_list[i] == search_item:
return i
else:
i -= 1
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_last_index(a_list, 'twitter'))
# Returns: 3
In the example above we loop over the list in reverse, by starting at the last index. We then evaluate if that item is equal to the search term. If it is we return the index position and the loop ends. Otherwise, we decrement the value by 1 using the augmented assignment operator.
Index of an Element Not Present in a Python List
By default, the Python list.index()
method will raise a ValueError
if an item is not present in a list. Let’s see what this looks like. We’ll search for the term 'pinterest'
in our list:
# Searching for an item that doesn't exist
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(a_list.index('pinterest'))
# Raises: ValueError: 'pinterest' is not in list
When Python raises this error, the entire program stops. We can work around this by nesting it in a try-except
block.
Let’s see how we can handle this error:
# Handling an error when an item doesn't exist
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
try:
print(a_list.index('pinterest'))
except ValueError:
print("Item doesn't exist!")
# Returns: Item doesn't exist!
Working with List Index Method Parameters
The Python list.index()
method also provides two additional parameters, start=
and stop=
. These parameters, respectively, indicate the positions at which to start and stop searching.
Let’s say that we wanted to start searching at the second index and stop at the sixth, we could write:
# Using Start and Stop Parameters in list.index()
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(a_list.index('twitter', 2, 6))
# Returns: 3
By instructing the method to start at index 2
, the method skips over the first instance of the string 'twitter'
.
Finding All Indices of Items Matching a Condition
In this final section, we’ll explore how to find the index positions of all items that match a condition. Let’s say, for example, that we wanted to find all the index positions of items that contain the letter 'y'
. We could use emulate the approach above where we find the index position of all items. However, we’ll add in an extra condition to our check:
# Finding Indices of Items Matching a Condition
def find_indices(search_list, search_item):
return [index for (index, item) in enumerate(search_list) if search_item in item]
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'y'))
# Returns:
# [0, 5]
The main difference in this function to the one shared above is that we evaluate on a more “fuzzy” condition.
Conclusion
In this tutorial, you learned how to use the index list method in Python. You learned how the method works and how to use it to find the index position of a search term. You also learned how to find the index positions of items that exist more than once, as well as finding the last index position of an item.
Finally, you learned how to handle errors when an item doesn’t exist as well as how to find the indices of items that match a condition.
Additional Resources
To learn more about related topics, check out the tutorials below:
- Python Lists: A Complete Overview
- Python Zip Lists – Zip Two or More Lists in Python
- Python IndexError: List Index Out of Range Error Explained
- Python List Index: Official Documentation