mode() function in Python statistics module (original) (raw)

The mode of a set of data values is the value that **appears most frequently. In statistics, it’s often used to understand the most common or popular value within a set. A mode of a continuous probability distribution is often considered to be any value '**x' at which its **probability density function has a local **maximum value, so any **peak is a **mode.

A dataset can have:

Python’s built-in statistics module provides a convenient **mode() function to compute this directly, for example:

Python `

import statistics

a = [1, 2, 3, 4, 4, 4, 5, 6, 7, 7, 7] res = statistics.mode(a) print("Mode:", res)

`

**Explanation: mode() method returns 4 from the list because it is the first value with the highest frequency.

Syntax

statistics.mode(data)

**Parameters:

**Return Type: It returns the most frequent value from the dataset.

**Raises: StatisticsError if the dataset is **empty.

In Python versions prior to **3.8, **statistics.mode() raises a StatisticsError if there is more than one most common value (no unique mode). From **Python 3.8 onwards, **statistics.mode() returns the **first mode encountered in case of multiple values with equal highest frequency. For reliable multi-mode analysis, use statistics.multimode().

Examples of mode()

Example 1: Mode with Different Datatypes

In this example, we will use mode() method over iterables containing various range of datatypes:

Python `

from statistics import mode from fractions import Fraction as fr

d1 = (2, 3, 3, 5, 5, 5, 6) d2 = (2.4, 1.3, 1.3, 2.4, 1.3) d3 = (fr(1, 2), fr(1, 2), fr(2, 3)) d4 = (-2, -2, -7, -7, -2) d5 = ("red", "blue", "blue", "black", "black", "black")

print("Mode 1:", mode(d1)) print("Mode 2:", mode(d2)) print("Mode 3:", mode(d3))
print("Mode 4:", mode(d4))
print("Mode 5:", mode(d5))

`

Output

Mode 1: 5 Mode 2: 1.3 Mode 3: 1/2 Mode 4: -2 Mode 5: black

**Explanation:

Example 2: Mode on an Empty List

Mode method throws a **StatisticsError if appliead over an empty iterable.

Python `

import statistics

a = []

print(statistics.mode(a))

`

**Output

Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 5, in
print(statistics.mode(a))
~~~~~~~~~~~~~~~^^^
File "/usr/local/lib/python3.13/statistics.py", line 785, in mode
raise StatisticsError('no mode for empty data') from None
statistics.StatisticsError: no mode for empty data

Example 3: Mode in a Real-World Context

In this example, mode() is used to determine the most popular subject among students:

Python `

from statistics import mode

s = ["Math", "Science", "English", "Math", "History", "Math", "Science"]

print("Most liked subject is:", mode(s))

`