Sometimes, we want to find all occurrences of an element in a list with Python.
In this article, we’ll look at how to find all occurrences of an element in a list with Python.
How to find all occurrences of an element in a list with Python?
To find all occurrences of an element in a list with Python, we can use list comprehension.
For instance, we write:
l = [1, 2, 3, 4, 3, 2, 5, 6, 7]
indexes = [i for i, val in enumerate(l) if val == 3]
print(indexes)
We use enumerate
to return an iterator with the tuples for the index and value of each l
array entry.
Then we get the i
index of each entry if their value is 3 by using the condition val == 3
.
And then we assign the array of indexes of the l
array where its values is 3 to indexes
.
Therefore, indexes
is [2, 4]
.
Conclusion
To find all occurrences of an element in a list with Python, we can use list comprehension.