Assume that we have the following list:
mylist = [1,1,1,2,2,3,3]
and we want to get the mode, i.e. the most frequent element. We can use the following trick using the max and the lambda key.
max(mylist, key = mylist.count)
And we get 1 since this was the mode in our list. In case where there is a draw in the mode and you want to get the minimum or the maximum number, you can sort the list as follows:
mylist = [1,1,1,2,2,3,3,3] max(sorted(mylist), key = mylist.count)
1
mylist = [1,1,1,2,2,3,3,3] max(sorted(mylist, reverse=True), key = mylist.count)
3
In the above example, we had two modes, 1 and 3. By adding the sorted
function we were able to get the min and the max respectively. Finally, this approach works with string elements too.
mylist = ['a','a','b','b','b'] max(mylist, key = mylist.count)
'b'