The statistics Module
Published by Brayan K
The statistics module is Python's built-in toolkit for calculating averages, spread, and quantiles directly on ordinary lists of numbers, with zero external dependencies.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Choose the question before choosing an average
A summary is useful only when you can say what it summarizes. The arithmetic mean distributes a total evenly across observations; the median locates the middle of the sorted observations; the mode identifies the most frequent value. They can disagree without any function being wrong.
from statistics import mean, median, mode
readings = [2, 3, 3, 4, 38]
print(mean(readings))
print(median(readings))
print(mode(readings))
# ✅ Expected output:
# 10
# 3
# 3Do not automatically delete the extreme reading. It might be a genuine event or a measurement error; that decision needs context. A median is less sensitive to the size of an extreme value, but it also discards information about that magnitude. Report the statistic that answers the intended question rather than choosing whichever looks nicer.
from statistics import median, median_low, median_high
values = [2, 4, 8, 10]
print(median(values))
print(median_low(values))
print(median_high(values))
# ✅ Expected output:
# 6.0
# 4
# 8median averages the two middle values for an even count. median_low and median_high select an actual middle observation on the respective side. That distinction matters when a result must be one of the observed categories or values. Do not use a numeric midpoint as if somebody actually measured it.
from statistics import mean
mean([])
# ✅ Expected error:
# statistics.StatisticsError: mean requires at least one data pointA tie is part of the result, not a random choice
from statistics import mode, multimode
labels = ["blue", "red", "red", "blue", "green"]
print(mode(labels))
print(multimode(labels))
print(multimode([]))
# ✅ Expected output:
# blue
# ['blue', 'red']
# []On the supported Python versions, mode returns the first encountered value among equally common values. multimode returns all most-common values in first-encounter order. Input order can therefore change a tie’s presentation. If the report requires alphabetical order, sort the multimode result explicitly and document that choice.
multimode of an empty input returns an empty list, while mode raises StatisticsError. Similar names do not imply identical empty-input contracts. Decide whether no observations is a valid “no result” state or an error before passing data into a report.
Population and sample variance use different denominators
from statistics import pvariance, variance, pstdev, stdev
values = [2, 4, 6]
print(pvariance(values))
print(variance(values))
print(round(pstdev(values), 4))
print(stdev(values))
# ✅ Expected output:
# 2.6666666666666665
# 4
# 1.633
# 2.0pvariance divides the sum of squared deviations by n and describes the supplied population. variance divides by n minus one and is the usual unbiased estimator of population variance under the independent, identically distributed sampling assumptions. Choosing the sample function does not repair a biased sample or prove those assumptions.
pstdev and stdev take the corresponding square roots. The unbiased-variance property does not make sample standard deviation itself an unbiased estimator. Variance has squared units; standard deviation has the original units. State which quantity a report contains instead of using “spread” as an ambiguous column label.
from statistics import variance
variance([5])
# ✅ Expected error:
# statistics.StatisticsError: variance requires at least two data pointsA one-observation population can have zero population variance, but the sample calculation cannot divide by n minus one. Silently returning zero for a missing or undersized sample would falsely suggest that variation was measured and absent.
Quantiles depend on the interpolation convention
from statistics import quantiles
values = [10, 20, 30, 40]
print(quantiles(values, n=4, method="exclusive"))
print(quantiles(values, n=4, method="inclusive"))
# ✅ Expected output:
# [12.5, 25.0, 37.5]
# [17.5, 25.0, 32.5]n=4 requests three cut points separating four intervals; it does not return four groups or four observations. The exclusive convention treats the sample as not necessarily containing the population extremes. The inclusive convention treats the minimum and maximum as the endpoints. Different conventions can legitimately produce different cut points.
Name the convention when comparing results with a spreadsheet or another library. Small datasets make the distinction especially visible. Avoid assuming a singleton has the same quantiles behavior on every supported Python release; these examples use enough observations for both conventions across Python 3.11–3.14.
Weighted and specialized means encode assumptions
from statistics import fmean
print(fmean([10, 20], weights=[1, 3]))
print(fmean([10, 20]))
# ✅ Expected output:
# 17.5
# 15.0fmean converts values to floating-point arithmetic and returns a float. Weights define relative contributions, so the two calls answer different questions. Validate that your application’s weights are meaningful and have the required sign and total. A weighted mean is not automatically appropriate merely because a weights parameter exists.
from statistics import mean, harmonic_mean, geometric_mean
speeds = [60, 40]
print(mean(speeds))
print(harmonic_mean(speeds))
print(round(geometric_mean([1, 4]), 6))
# ✅ Expected output:
# 50
# 48.0
# 2.0For equal amounts of time at the two speeds, total distance divided by total time gives the arithmetic mean. For equal distances, the durations differ, so the harmonic mean gives the overall speed. “Use the harmonic mean for rates” is incomplete without the weighting assumption. The geometric mean summarizes multiplicative positive factors; it is not a general replacement for either rate calculation.
Validate all inputs before specialized calculations if your domain forbids zero, negative or nonfinite values. Some functions can short-circuit on zero, so relying on a later invalid element to raise is an unreliable validation strategy.
Choose a missing-value policy and a consistent numeric type
from math import isfinite
from statistics import mean
raw = [10.0, float("nan"), 20.0, float("inf")]
clean = [value for value in raw if isfinite(value)]
print(len(raw) - len(clean))
print(mean(clean))
# ✅ Expected output:
# 2
# 15.0NaN does not behave like an ordinary sortable number, which can produce surprising medians, modes and quantiles. This example deliberately excludes all nonfinite values and reports how many it excluded. Another application may need to reject the whole batch. The policy belongs in the surrounding program; a statistic cannot decide what missing data means.
from decimal import Decimal
from statistics import mean, fmean
values = [Decimal("0.1"), Decimal("0.2")]
result = mean(values)
print(result)
print(type(result).__name__)
print(type(fmean(values)).__name__)
# ✅ Expected output:
# 0.15
# Decimal
# floatUse a consistent supported numeric type. Arbitrary mixtures of Decimal, Fraction and float are not a portable statistics contract. Numbers: int, float, Decimal & Fraction owns representation, precision and conversion decisions. Also remember that an iterator is consumed by a calculation: materialize a small dataset once when several summaries must inspect the same observations.
Complete a report that states its population contract
This fixture is the complete set of readings for one batch. Calculate its median and population variance, and report its size. The literal hints select the two statistics.
from statistics import median, pvariance
readings = [2, 4, 6, 8]
print(len(readings))
print(___(readings))
print(___(readings))
# 👉 replace ___ with median
# 👉 replace ___ with pvariance
# ✅ Expected output:
# 4
# 5.0
# 5Summarize a batch without disguising rejected data
Given the floating-point readings 2, 4, NaN, 4, 10 and infinity, keep finite observations and report accepted and rejected counts. Treat accepted readings as the complete observed batch, then print the mean, median, sorted modes and population variance. Reject the report if no accepted values remain. Make the missing-value and population choices visible in your code.
from math import isfinite
from statistics import mean, median, multimode, pvariance
raw = [2.0, 4.0, float("nan"), 4.0, 10.0, float("inf")]
accepted = [value for value in raw if isfinite(value)]
if not accepted:
raise ValueError("no finite observations")
print("accepted:", len(accepted))
print("rejected:", len(raw) - len(accepted))
print("mean:", mean(accepted))
print("median:", median(accepted))
print("modes:", sorted(multimode(accepted)))
print("population variance:", pvariance(accepted))
# ✅ Expected output:
# accepted: 4
# rejected: 2
# mean: 5.0
# median: 4.0
# modes: [4.0]
# population variance: 9.0
Practice quiz
What does this program print? from statistics import median print(median([2, 4, 8, 10]))
- 6.0
- 4
- 8
- 5
Answer: 6.0. The even-sized median averages the middle pair.
What does this program print? from statistics import mode print(mode(["B", "A", "A", "B"]))
- A
- B
- ["A", "B"]
- StatisticsError
Answer: B. A tied mode returns the first encountered tied value.
What does this program print? from statistics import pvariance, variance print(pvariance([2, 4])) print(variance([2, 4]))
- 2 1
- 1 1
- 1 2
- 2 2
Answer: 1 2. The population denominator is two, while the sample denominator is one.
What does quantiles(data, n=4) produce?
- Four groups of original observations
- Four means
- A unique convention-independent median
- Three cut points under a selected interpolation convention
Answer: Three cut points under a selected interpolation convention. Quantiles define interval boundaries rather than grouping the original records.
What does this program print? from statistics import fmean print(fmean([10, 20], weights=[1, 3]))
- 17.5
- 15.0
- 30.0
- 7.5
Answer: 17.5. The weighted total is divided by the total weight.
When is the ordinary harmonic mean appropriate for two travel speeds?
- For any two rates regardless of weighting
- When the two segments cover equal distances
- Only when both speeds are identical
- Whenever the arithmetic mean is larger
Answer: When the two segments cover equal distances. Equal distances give unequal durations; equal-time segments use the arithmetic mean instead.
What does this program print? from statistics import multimode print(multimode([]))
- None
- StatisticsError
- []
- 0
Answer: []. multimode explicitly returns an empty list for no observations.
What should happen before computing an ordered statistic from readings containing NaN?
- Treat NaN as zero automatically
- Assume sorting places it last
- Ignore the issue because all statistics handle it identically
- Apply and report an explicit missing-value policy
Answer: Apply and report an explicit missing-value policy. NaN comparison behavior can undermine a meaningful ordering; the surrounding program must choose the policy.
Continue this course
- Previous: Checkpoint: Concurrency & I/O
- Next: The operator Module — Use itemgetter, attrgetter and operator functions for fast, clean code
- Quick reference: Python cheat sheet