Iterate with Enumerate
You are given a list of items and one target value. Your job is to find every index where the target appears and return those indices in a new list.
The important part is that the answer should contain positions, not the matching elements themselves. If the target occurs multiple times, you include every matching index from left to right. If the target never appears, the result should be an empty list.
For example, if items = ["apple", "banana", "apple", "cherry"] and target = "apple", the answer is [0, 2] because those are the positions where the target appears. If the list is empty, the answer is just [].
So the task is to scan the list while keeping track of both the current item and its index, then collect the indices where the item matches the target.
Example Input & Output
A single matching element produces its one index.
Every index where the target appears is collected from left to right.
An empty input list cannot contain the target, so the result is empty.
Algorithm Flow

Solution Approach
This problem is a very natural use case for Python's enumerate() function. A normal loop over a list gives you the values one by one, but this problem needs both the value and its index at the same time. That is exactly what enumerate() is built for.
When you write something like for index, item in enumerate(items), Python produces pairs containing the current position and the current element. That means you do not have to manually track a separate counter variable.
A clean solution is:
This list comprehension does three things at once. It loops through the input list with enumerate(), checks whether the current item matches the target, and if it does, keeps the corresponding index.
This approach is especially nice because it expresses the exact rule of the problem: return all indices whose values match the target. It also naturally handles edge cases. If the target appears several times, every matching index is included. If the target never appears, the comprehension simply produces an empty list.
You could write the same logic with a regular loop and append(), and that would be perfectly correct:
The comprehension version is simply shorter while keeping the same meaning. It is also a good demonstration of why enumerate() is preferable to manually incrementing an index variable in most Python code.
That preference is not just style. Manual counters create more room for off-by-one mistakes or forgotten increments. enumerate() removes that bookkeeping and lets the code focus on the actual matching rule.
The runtime is O(n) because every item is checked once, and the extra space depends on how many matching indices end up in the result list.
Best Answers
def find_element_indices(items, target):
# Approach 1: Highly Pythonic List Comprehension with enumerate()
return [index for index, item in enumerate(items) if item == target]Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
