← Back to Python Course | Chapter 13: Data Science & Web | Lesson 7 of 14

Python Statistics Module

Central Tendency

The built-in statistics module offers simple, dependency-free functions for common calculations: statistics.mean() computes the arithmetic average and statistics.median() finds the middle value of a sorted dataset, which is more robust to outliers than the mean.

Example: Central Tendency

python
import statistics
data = [1, 2, 3, 4, 100]
print(statistics.mean(data))
print(statistics.median(data))

Mode and Frequency

statistics.mode() returns the single most frequently occurring value in a dataset, while statistics.multimode() returns all values tied for the most frequent when there's more than one. Mode is the only measure of central tendency that also makes sense for non-numeric, categorical data.

Example: Mode and Frequency

python
import statistics
data = [1, 2, 2, 3]
print(statistics.mode(data))
print(statistics.multimode([1, 1, 2, 2, 3]))

Dispersion Measures

statistics.variance() and statistics.stdev() quantify how spread out a dataset's values are around the mean -- a small standard deviation means values cluster tightly, a large one means they're widely scattered. Both come in population and sample variants (pvariance/pstdev vs variance/stdev), and picking the wrong one skews results for small datasets.

Example: Dispersion Measures

python
import statistics
data = [2, 4, 4, 4, 5, 5, 7, 9]
print(statistics.variance(data))
print(statistics.stdev(data))

Data Distribution Ranges

statistics.median_low() and statistics.median_high() resolve the ambiguity that arises when a dataset has an even number of values and there's no single middle element -- they return the lower and upper of the two central values respectively, instead of averaging them.

Example: Data Distribution Ranges

python
import statistics
data = [1, 2, 3, 4]
print(statistics.median_low(data))
print(statistics.median_high(data))

Harmonic and Geometric Means

statistics.geometric_mean() and statistics.harmonic_mean() are specialized averages suited to specific situations: geometric mean is appropriate for averaging rates of growth or ratios, and harmonic mean is appropriate for averaging rates like speed, where the arithmetic mean would give a misleading answer.

Example: Harmonic and Geometric Means

python
import statistics
data = [2, 8]
print(statistics.geometric_mean(data))
print(statistics.harmonic_mean(data))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.