Last Updated : 11 Jul, 2025
In Python, it is common to locate the index of a particular value in a list. The built-in index()
method can find the first occurrence of a value. However, there are scenarios where multiple occurrences of the value exist and we need to retrieve all the indices. Python offers various methods to achieve this efficiently. Let’s explore them.
List comprehension is an efficient way to find all the indices of a particular value in a list. It iterates through the list using enumerate()
checking each element against the target value.
a = [4, 7, 9, 7, 2, 7]
# Find all indices of the value 7
indices = [i for i, x in enumerate(a) if x == 7]
print("Indices", indices)
Explanation of Code:
enumerate(a)
generates pairs of index and value from the list.if x == 7
filters indices where the value is 7
.Let's explore some other methods on ways to find indices of value in list.
Usingindex()
Method
The index()
method can be used iteratively to find all occurrences of a value by updating the search start position. This is particularly useful if only a few occurrences need to be located.
Example:
Python
a = [4, 7, 9, 7, 2, 7]
# Find all indices of the value 7
indices = []
start = 0
while True:
try:
index = a.index(7, start)
indices.append(index)
start = index + 1
except ValueError:
break
print("Indices", indices)
Explanation:
a.index(7, start)
begins searching for 7
starting from the start
index.ValueError
exception ends the loop when no more occurrences are found.NumPy is a popular library for numerical computations. Converting the list to a NumPy array and using the where()
function makes locating indices of a value efficient and concise.
import numpy as np
a = [4, 7, 9, 7, 2, 7]
# Convert list to NumPy array
arr = np.array(a)
# Find all indices of the value 7
indices = np.where(arr == 7)[0]
print("Indices", indices.tolist())
Explanation:
np.where(arr == 7)
identifies positions where the array's value matches 7
.A loop provides a straightforward way to iterate through the list and collect indices of matching values. This is useful when conditions beyond equality are required.
Python
a = [4, 7, 9, 7, 2, 7]
# Find all indices of the value 7
indices = []
for i in range(len(a)):
if a[i] == 7:
indices.append(i)
print("Indices", indices)
Explanation:
a[i] == 7
filters indices with the target value.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4