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:

  1. Count the frequency of each value in the list.
  2. 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()

Calculating Mode in Python The statistics.mode() return the most common data point from discrete or nominal data. Python 3.4 includes the method statistics.mode, so it is straightforward:
>>> 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