Find All Occurrences of an Item in a Python List

Loop through a list with enumerate() to collect the index of every match for a target value.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

16 lines
Python 3.9+
def find_all(data, target):
    """Return indices of every occurrence of target in a list."""
    indices = []
    for index, item in enumerate(data):
        if item == target:
            indices.append(index)
    return indices


if __name__ == "__main__":
    sample = [10, 20, 30, 20, 40, 20, 50]
    target_value = 20
    result = find_all(sample, target_value)
    print(f"List: {sample}")
    print(f"Target: {target_value}")
    print(f"Indices found: {result}")

Output

stdout
List: [10, 20, 30, 20, 40, 20, 50]
Target: 20
Indices found: [1, 3, 5]

How it works

The enumerate(data) call pairs each item with its index, so the loop gets both at once. Each time item == target, that index is appended to indices. This approach is O(n) — it scans the list once. It works for any comparable type, not just integers. The helper returns an empty list when no matches exist, which is easy to check with if result:.

Common mistakes

  • Using `list.index()` which only returns the first match
  • Forgetting that indices start at 0, not 1
  • Mutating the list while iterating over it

Variations

  1. Use a list comprehension: `[i for i, v in enumerate(data) if v == target]`
  2. For NumPy arrays, use `np.where(arr == target)[0]`

Real-world use cases

  • Finding all positions of a specific user ID in a session log for auditing.
  • Locating every error code in a list of returned statuses during batch processing.
  • Identifying all duplicates of a product SKU in an inventory list for cleanup.

Sponsored

Run this sample

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

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.