BudiBadu Logo

Iterate with Enumerate

Python Easy 21 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.

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]