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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

8 lines
Python 3.9+
def 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

stdout
[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

  1. Use a traditional for loop with an explicit results list for more control or readability.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.