Find All Indices of a Target Value in a Python List
Returns a list of all indices where a given target value appears in a Python list using a list comprehension with enumerate.
Python code
8 linesdef find_all_indices(arr, target):
return [i for i, value in enumerate(arr) if value == target]
if __name__ == "__main__":
sample_list = [4, 2, 7, 2, 9, 2, 1, 2]
target = 2
result = find_all_indices(sample_list, target)
print(result)
Output
[1, 3, 5, 7]
How it works
The function uses enumerate(arr) to get both the index and value of each element in the list. The list comprehension [i for i, value in enumerate(arr) if value == target] builds a new list containing only the indices where the value equals the target. This approach is efficient with a time complexity of O(n), visiting each element exactly once. It returns an empty list if the target is not found, which is often more useful than raising an error.
Common mistakes
- Forgetting that `enumerate` returns a tuple; make sure to unpack both index and value in the comprehension.
- Using `arr.index(target)` which only returns the first occurrence, not all.
- Modifying the list while iterating, which can cause skipped indices or errors.
Variations
- Use a traditional for loop with an explicit results list for more control or readability.
- Use `filter` with `enumerate` to find indices functionally.
Real-world use cases
- Locating all occurrences of a specific error code in a log list to trigger multiple alerts.
- Finding every index of a duplicate item in an inventory list to clean up or merge records.
- Identifying all positions of a keyword in a text token list for further NLP processing.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.