Python Statistics Module

The statistics module provides simple tools for calculating averages, medians, and other descriptive statistics.

The module was added in Python 3.4.

import statistics

Use statistics when you need common calculations for a small list of numbers. For advanced data analysis, libraries like NumPy and pandas are more powerful, but they are not part of the standard library.

mean()

import statistics

scores = [80, 90, 95, 100]
print(statistics.mean(scores))
91.25

fmean returns a floating-point mean and is often faster for numeric data:

import statistics

print(statistics.fmean([1, 2, 3]))
2.0

median()

import statistics

values = [1, 3, 5, 100]
print(statistics.median(values))
4.0

mode()

mode returns the most common value.

import statistics

print(statistics.mode(['python', 'python', 'rust']))
python

If more than one value is common, multimode returns all of them:

import statistics

print(statistics.multimode(['red', 'blue', 'red', 'blue']))
['red', 'blue']

stdev()

stdev calculates the sample standard deviation.

import statistics

print(round(statistics.stdev([2, 4, 4, 4, 5, 5, 7, 9]), 2))
2.14

Handling empty data

Most functions raise StatisticsError for empty input.

import statistics

try:
    statistics.mean([])
except statistics.StatisticsError as error:
    print(type(error).__name__)
StatisticsError