Summarize Samples with statistics
Core idea
Use mean for the arithmetic average and median for the middle of sorted data (averaging the middle pair for even counts). Standard deviation measures spread in the original units: stdev estimates sample spread using n-1; pstdev describes an entire population using n.
from statistics import mean, medianreadings = [2, 3, 25]print(mean(readings), median(readings))The large reading shifts the mean more than the median.
Compare population and sample spread
from statistics import stdev, pstdevvalues = [2, 4, 6]print(stdev(values), round(pstdev(values), 3))The sample denominator is smaller, so sample deviation is larger here.
Handle an empty sample
from statistics import median, StatisticsErrortry: median([])except StatisticsError: print("no readings")An empty dataset has no median; report missing data instead of inventing zero.
Common mistake
Remove or explicitly handle NaN before sorting-based statistics. stdev needs at least two observations; choose a consistent numeric type and check the domain.
Practice
Compute the median for odd and even nonempty samples and compare with the mean after adding an outlier.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sample summaries
Check your understanding of statistics.
What is printed?
from statistics import medianprint(median([3,7]))What is printed?
from statistics import mean, medianprint(mean([2,4,18]), median([2,4,18]))Which exception occurs?
from statistics import stdevstdev([5])Which function describes spread of a complete population?