BudiBadu Logo

Iterate with Enumerate

Python Easy 7 views
Like0

Often, when iterating through a list, you need both the element itself and its index (position). While beginners from other languages might instinctively reach for for i in range(len(items)):, the Pythonic way is far more elegant: the built-in enumerate() function.

enumerate() wraps an iterable and yields pairs of (index, element) across each step of the loop. It's clean, highly readable, and eliminates the need for manual counter variables.

Your objective is to write a function that takes a list of items and a target string. Using enumerate(), find all the index positions where the target string appears in the list, and return those indices as a new list.

Example 1:

Input: items = ["apple", "banana", "apple", "cherry"], target = "apple"
Output: [0, 2]
Explanation: The word "apple" appears at index 0 and index 2.

Example 2:

Input: items = ["cat", "dog", "bird"], target = "fish"
Output: []
Explanation: The target does not exist in the list.

Constraints:

  • The list length will be between 0 and 1000 items.
  • Elements and the target will be standard strings.

Algorithm Flow

Recommendation Algorithm Flow for Iterate with Enumerate - Budibadu
Recommendation Algorithm Flow for Iterate with Enumerate - Budibadu

Best Answers

python - Approach 1
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]