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.
Python code
16 linesdef 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
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
- Use a list comprehension: `[i for i, v in enumerate(data) if v == target]`
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find Duplicate Elements in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.