How to find all occurrences of an element in a list with Python?

Estimated read time 2 min read

To find all occurrences of an element in a list in Python, you can use the enumerate() function or a list comprehension. Here’s an example for each approach:

  1. Using the enumerate() function:
my_list = [2, 4, 6, 2, 8, 2, 10, 2]
element = 2

occurrences = [index for index, value in enumerate(my_list) if value == element]

print(occurrences)

In this example, we have a list my_list and an element element that we want to find. We use a list comprehension to iterate over the elements of my_list along with their corresponding indices using the enumerate() function. If the current element matches the target element, we add the index to the occurrences list.

  1. Using a list comprehension:
my_list = [2, 4, 6, 2, 8, 2, 10, 2]
element = 2

occurrences = [index for index in range(len(my_list)) if my_list[index] == element]

print(occurrences)

In this example, we again have a list my_list and an element element. We use a list comprehension to iterate over the indices of my_list using the range() function. If the element at the current index matches the target element, we add the index to the occurrences list.

Both approaches provide the same output, which is a list of indices representing the occurrences of the target element within the list.

You can adjust the list name (my_list) and the target element (element) according to your specific needs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply