Use the statistics module to summarize small numerical datasets.
What It Does and Why It Matters
statistics provides averages, medians, modes, variance, correlation, regression, and a NormalDist class without third-party packages. Different functions require different minimum sample sizes; the library is not a substitute for domain-appropriate statistical methods.
Missing values, NaNs, units, and sample-selection bias need deliberate handling before computing statistics.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
import statistics
measurements = [12, 14, 16, 20]
print(statistics.mean(measurements))
print(statistics.median(measurements))
print(round(statistics.pstdev(measurements), 3))
How the Code Works
- The imports make these standard-library tools available: statistics.
- The name measurements receives the value of [12, 14, 16, 20]. Changing this input lets you explore a different case.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
15.5
15.0
2.958
Each displayed line comes from the corresponding calculation or check. The output helps verify the return values before you adapt the example to your own input.
What to Notice
Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.
If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.
Where You Would Use This
Use the technique when it makes a real task easier to understand or safer to maintain. Check input and output behavior with small tests before combining it with larger application code.
Practice Exercise
Summarize five response-time measurements using mean, median, and dispersion.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Mixing a sample standard-deviation formula with population data without choosing the right function.
- Overlooking the documented condition: different functions require different minimum sample sizes; the library is not a substitute for domain-appropriate statistical methods.
Key Takeaways
- Use the statistics module to summarize small numerical datasets.
- statistics provides averages, medians, modes, variance, correlation, regression, and a NormalDist class without third-party packages.
- Summarize five response-time measurements using mean, median, and dispersion.