Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Ways to find indices of value in list
Finding indices of specific values in a list is a common task in Python programming. While the index() method finds the first occurrence, there are several ways to find all indices where a particular value appears in a list.
Using enumerate()
The enumerate() function returns both index and value, making it perfect for this task ?
# initializing list
numbers = [1, 3, 4, 3, 6, 7]
print("Original list :", numbers)
# using enumerate() to find indices for 3
indices = [i for i, value in enumerate(numbers) if value == 3]
print("Indices of 3 :", indices)
Original list : [1, 3, 4, 3, 6, 7] Indices of 3 : [1, 3]
Using List Comprehension with range()
This approach uses range() to iterate through indices and checks values at each position ?
# initializing list
numbers = [1, 3, 4, 3, 6, 7]
print("Original list :", numbers)
# using list comprehension with range()
indices = [i for i in range(len(numbers)) if numbers[i] == 3]
print("Indices of 3 :", indices)
Original list : [1, 3, 4, 3, 6, 7] Indices of 3 : [1, 3]
Using filter() Function
The filter() function can filter indices based on a condition using a lambda function ?
# initializing list
numbers = [1, 3, 4, 3, 6, 7]
print("Original list :", numbers)
# using filter() to find indices for 3
indices = list(filter(lambda x: numbers[x] == 3, range(len(numbers))))
print("Indices of 3 :", indices)
Original list : [1, 3, 4, 3, 6, 7] Indices of 3 : [1, 3]
Using Traditional Loop
A simple for loop approach that manually checks each element ?
# initializing list
numbers = [1, 3, 4, 3, 6, 7]
print("Original list :", numbers)
# using traditional loop to find indices for 3
indices = []
for i in range(len(numbers)):
if numbers[i] == 3:
indices.append(i)
print("Indices of 3 :", indices)
Original list : [1, 3, 4, 3, 6, 7] Indices of 3 : [1, 3]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
enumerate() |
High | Fast | Most Pythonic approach |
| List comprehension | High | Fast | Simple one-liner |
filter() |
Medium | Moderate | Functional programming style |
| Traditional loop | High | Moderate | Beginners, complex conditions |
Conclusion
The enumerate() method is generally the most Pythonic and readable approach for finding all indices of a value. Use list comprehension for simple one-liners or traditional loops when you need more complex logic during iteration.
