Home > Article > Backend Development > How to Efficiently Find the Most Common Element in a Python List, Even With Non-Hashable Items?
Finding the Most Common Element in a List Efficiently
In Python, determining the most frequently occurring element in a list can pose a challenge, especially when list items are not hashable. To address this, we present an efficient approach that prioritizes the item with the lowest index in case of ties.
Consider the following Python function:
def most_common(lst): return max(set(lst), key=lst.count)
This function operates by eliminating duplicates from the input list lst by converting it to a set. The max() function is then utilized to identify the element with the highest count from the set. The key parameter specifies that the comparison should be based on the count of each element, as determined by the lst.count method.
To illustrate, consider these examples:
>>> most_common(['duck', 'duck', 'goose']) 'duck'
In this instance, 'duck' occurs twice, while 'goose' appears only once. Hence, 'duck' is returned as the most common element.
>>> most_common(['goose', 'duck', 'duck', 'goose']) 'goose'
In this scenario, both 'goose' and 'duck' occur twice. However, since 'goose' possesses a lower index, it is returned as the most common element.
This approach effectively finds the most common element in a list, even when the elements are not hashable, and it prioritizes the item with the lowest index in case of ties.
The above is the detailed content of How to Efficiently Find the Most Common Element in a Python List, Even With Non-Hashable Items?. For more information, please follow other related articles on the PHP Chinese website!