Home >Backend Development >Python Tutorial >How Can I Find All Occurrences of an Element in a Python List?

How Can I Find All Occurrences of an Element in a Python List?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 16:35:10216browse

How Can I Find All Occurrences of an Element in a Python List?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn