Code Reference

Statistics

Python · Reference cheat sheet

Statistics

Python · Reference cheat sheet


📋 Overview

statistics is the stdlib module for basic descriptive stats on numeric data. For heavy analysis and DataFrames, prefer pandas / NumPy.

🔧 Core concepts

APIRole
mean / fmeanArithmetic mean (fmean faster for floats)
median / modeMiddle value / most common
pstdev / stdevPopulation / sample stdev
pvariance / varianceVariance
quantilesCut points
correlationPearson correlation (3.10+)

💡 Examples

from statistics import mean, median, mode, stdev

xs = [2, 4, 4, 4, 5, 5, 7, 9]
print(mean(xs), median(xs), mode(xs))
print(stdev(xs))
from statistics import quantiles, correlation

data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(quantiles(data, n=4))  # quartiles
print(correlation([1, 2, 3], [2, 4, 6]))

⚠️ Pitfalls

  • Empty sequences raise StatisticsError.
  • mode raises if no unique mode (use multimode).
  • Sample vs population (stdev vs pstdev) — know which you need.
  • Not a substitute for pandas groupby / NumPy vectorized ops on large data.

On this page