Python - Ways to find indices of value in list
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.
Using List Comprehension
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)
Output
Indices [1, 3, 5]
Explanation of Code:
enumerate(a)
generates pairs of index and value from the list.- The condition
if x == 7
filters indices where the value is7
.
Let's explore some other methods on ways to find indices of value in list.
Table of Content
Using index()
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:
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)
Output
Indices [1, 3, 5]
Explanation:
a.index(7, start)
begins searching for7
starting from thestart
index.- The
ValueError
exception ends the loop when no more occurrences are found.
Using NumPy
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())
Output
Indices [1, 3, 5]
Explanation:
np.where(arr == 7)
identifies positions where the array's value matches7
.
Using For Loop
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.
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)
Output
Indices [1, 3, 5]
Explanation:
- The loop iterates over the indices of the list.
- The condition
a[i] == 7
filters indices with the target value.