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.

PythonData Integrity

Code

pythonsnippet
19 lines
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.0

How 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

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`.