Finding All Occurrences of an Element in a List
The Python function index() can be used to find the first occurrence of an item in a list. However, there may be situations where you need to retrieve all occurrences of a specific element.
To achieve this, a clever solution involves using list comprehension with the enumerate() function:
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
The enumerate() function generates pairs of (index, item) for each item in the list. By unpacking these pairs into the index i and the list item x, the list comprehension creates a new list containing the indices of all elements in my_list that are equal to "whatever."
The above is the detailed content of How Can I Find All Occurrences of an Element in a Python List?. For more information, please follow other related articles on the PHP Chinese website!