Find most frequent element in a list in Python

PythonServer Side ProgrammingProgramming

In this article we will see how to find the element which is most common in a given list. In other words, the element with highest frequency.

With max and count

We apply why the set function to get the unique elements of the list and then keep account of each of those elements in the list. Finally apply a max function to get the element with highest frequency.

Example

 Live Demo

# Given list
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("Given List:\n",listA)
res = max(set(listA), key = listA.count)
print("Element with highest frequency:\n",res)

Output

Running the above code gives us the following result −

Given List:
[45, 20, 11, 50, 17, 45, 50, 13, 45]
Element with highest frequency:
45

With Counter

We use the counter function from collections. Then apply the most common function to get the final result.

Example

 Live Demo

from collections import Counter
# Given list
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("Given List:\n",listA)
occurence_count = Counter(listA)
res=occurence_count.most_common(1)[0][0]
print("Element with highest frequency:\n",res)

Output

Running the above code gives us the following result −

Given List:
[45, 20, 11, 50, 17, 45, 50, 13, 45]
Element with highest frequency:
45

With mode

This is a straight forward approach in which we use the mode function from statistics module. It directly gives us the result.

Example

from statistics import mode
# Given list
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("Given List:\n",listA)
res=mode(listA)
print("Element with highest frequency:\n",res)

Output

Running the above code gives us the following result −

Given List:
[45, 20, 11, 50, 17, 45, 50, 13, 45]
Element with highest frequency:
45
raja
Published on 04-Jun-2020 15:13:29
Advertisements