Finding the mode of a list
You can use the max
function and a key. Have a look at python max function using 'key' and lambda expression.
max(set(lst), key=lst.count)
You can use the Counter
supplied in the collections
package which has a mode
-esque function
from collections import Counterdata = Counter(your_list_in_here)data.most_common() # Returns all unique items and their countsdata.most_common(1) # Returns the highest occurring item
Note: Counter is new in python 2.7 and is not available in earlier versions.
Python 3.4 includes the method statistics.mode
, so it is straightforward:
>>> from statistics import mode>>> mode([1, 1, 2, 3, 3, 3, 3, 4]) 3
You can have any type of elements in the list, not just numeric:
>>> mode(["red", "blue", "blue", "red", "green", "red", "red"]) 'red'