How to find occurrences?

0124

To find all occurrences of a specific element in a list, you can create a function called find_indices(). Here’s an example in Python:

def find_indices(my_list, element):
    return [index for index, value in enumerate(my_list) if value == element]

# Example usage
my_list = [1, 2, 3, 4, 2, 2, 5]
element = 2
indices = find_indices(my_list, element)
print(indices)  # Output: [1, 4, 5]

In this code, the find_indices() function takes a list and an element as parameters and returns a list of all indices where the element appears in the list.

0 Comments

no data
Be the first to share your comment!