Finding the mode of a list | Python
>>> myList = [10, 20, 20, 30, 30 ,30, 40]
>>> max(set(myList), key=myList.count)
30
Python mod()
Mode is a descriptive statistic that is used as a measure of central tendency of a distribution. It is equal to value that occurs the most frequently. This means that mode is a value or element that appears with the highest frequency. There can be one mode, more than one mode, or no mode at all. There will be no mode if all the elements are unique. There are several ways to determine the mode in Python and this lesson will discuss some of those methodologies.To calculate the mode of a list of values:
- Count the frequency of each value in the list.
- The value with the highest frequency is the mode.
Using Python max()
max(players, key=func)
The max() function is used to get the maximum out of an iterable.
>>> myList = [10, 20, 20, 30, 30 ,30, 40]
>>> print(max(set(myList), key=myList.count))
30
Using statistics.mode()

>>> from statistics import mode
>>> myList = [10, 20, 20, 30, 30 ,30, 40]
>>> print(mode(myList))
30
This function will raise the StatisticsError when the data set is empty or when more than one mode is present. However, in the newer versions of Python, the smallest element will be considered the mode when there are multiple modes of a sequence.
Using collections.Counter()
A Counter is a dict subclass for counting hashable objects. You can use the Counter supplied in the collections package which has a mode-esque function.
>>> from collections import Counter
>>> myList = [10, 20, 20, 30, 30 ,30, 40]
>>> mData = Counter(myList)
>>> print(mData.most_common())
>>> print(mData.most_common(1))
Output:
[(30, 3), (20, 2), (10, 1), (40, 1)]
[(30, 3)]
Finding mod without using Python library
Following Python program finding the mode of a list without using any Python library.
def findMode(inList):
modeList = {}
for item in inList:
if item in modeList:
modeList[item] += 1
else:
modeList[item] = 1
return [key for key in modeList.keys() if modeList[key] == max(modeList.values())]
myList = [10, 20, 20, 30, 30 ,30, 40]
print(findMode(myList))
Output:
30
Related Topics
- How to use Date and Time in Python
- Python Exception Handling
- How to Generate a Random Number in Python
- How to pause execution of program in Python
- How do I parse XML in Python?
- How to read and write a CSV files with Python
- Threads and Threading in Python
- Python Multithreaded Programming
- Python range() function
- How to Convert a Python String to int
- Python filter() Function
- Difference between range() and xrange() in Python
- How to print without newline in Python?
- How to remove spaces from a string in Python
- How to get the current time in Python
- Slicing in Python
- Create a nested directory without exception | Python
- How to measure time taken between lines of code in python?
- How to concatenate two lists in Python
- Difference Between Static and Class Methods in Python?