A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-ways-to-find-indices-of-value-in-list/ below:

Python - Ways to find indices of value in list

Python - Ways to find indices of value in list

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.

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.

Python
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:

Let's explore some other methods on ways to find indices of value in list.

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:

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: 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.

Python
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: 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.

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:

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