statistics.correlation Measures Linear Association
correlation() returns the Pearson coefficient between two series while covariance() keeps raw units; self-correlation is 1 and linear rescaling preserves r.
Code
from statistics import correlation, covariance
practice_hours = [2, 3, 4, 5, 6, 8]
defect_count = [12, 10, 9, 7, 6, 3]
# Pearson r: linear association scaled to -1..1
r = correlation(practice_hours, defect_count)
print(f"practice vs defects r = {r:.3f}")
cov = covariance(practice_hours, defect_count)
print(f"covariance = {cov:.2f}")
# A series correlates with itself perfectly
print(f"self = {correlation(practice_hours, practice_hours)}")
# Linear rescaling keeps r: Celsius vs Fahrenheit track perfectly
celsius = [10, 15, 20, 25]
fahrenheit = [50, 59, 68, 77]
print(f"celsius vs fahrenheit = {correlation(celsius, fahrenheit)}")Output
Captured from a sandboxed run of this snippet in the build pipeline.
practice vs defects r = -0.997
covariance = -6.87
self = 1.0
celsius vs fahrenheit = 1.0How it works
The file’s state is a handful of top-level bindings: practice_hours, defect_count, cov, celsius.
Points of care
- No import goes further than the runtime itself, so the file stands alone.
Using it
The run emits 4 labeled sections — practice vs defects r =, covariance =, self =, celsius vs fahrenheit = — one per step.
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Statistics CalculatorCompute count, sum, mean, median, minimum, maximum, range, variance, and standard deviation for a number list.Text StatisticsCount characters, words, lines, sentences, paragraphs, and estimated reading time entirely in the browser with no text sent to a server.
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. Every import resolves inside the standard library — `statistics`. Its state lives in module-level bindings: `practice_hours`, `defect_count`, `cov`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.