Find element with most number of occurrences in list
Find element with most number of occurrences in list
To find the element with most number of occurrences in given list in Python, call max() built-in function, with list count()
method passed as value for key
parameter to max() function.
The syntax to find the most occurred element in the list x
max(x, key=x.count)
The max() function compares the elements in the list x
based on the return value from key function, which is the number of occurrences of an element in the list.
And in this use case, the max() function returns the element with most number of occurrences.
Examples
1. Find most occurred element in list x
In the following program we take a list of numbers in x
, and find the element with most number of occurrences in the list using max() function.
Python Program
x = [2, 4, 0, 2, 8, 4, 2, 10]
mostFrequent = max(x, key=x.count)
print(mostFrequent)
Output
2
The element 2
has occurred three times, the most, which no other element has done.
2. If there are more than one element with most number of occurrences in the list
If there are more than one element with most number of occurrences in the list, then the element that appears first in the list is returned by max() function.
In the following program there are two elements with most number of occurrences in the list: 4
and 2
. The first element 4
is returned by the max() function.
Python Program
x = [4, 2, 0, 2, 8, 4, 4, 2, 10]
mostFrequent = max(x, key=x.count)
print(mostFrequent)
Output
4
Summary
In this tutorial of Python Examples, we learned how to find the most occurred element in the list using max() builtin function, with the help of examples.