Python 3.10+statisticsfunction
statistics.correlation
relationships
Pearson's (or Spearman's) correlation coefficient of two datasets, −1..1 (3.10+).
Syntax
statistics.correlation(x, y)
It detects straight-line relationships only: y = x² on a symmetric dataset scores near zero despite being perfectly determined, and a high score says nothing about cause. Both inputs must have the same length and at least two values, and a constant sequence (zero spread) raises StatisticsError. Spearman's version requires method='ranked', which exists only from 3.12.
Examples
import statistics
print(statistics.correlation([1, 2, 3], [2, 4, 6])) # → 1.0
print(statistics.correlation([1, 2, 3], [6, 4, 2])) # → -1.0
print(statistics.correlation([1, 2, 3, 4], [1, 3, 2, 4])) # → 0.8
print(statistics.correlation([1, 1, 1], [1, 2, 3])) # → StatisticsError
# Python 3.12+
import statistics
print(statistics.correlation([1, 2, 3], [10, 30, 20], method='ranked')) # → 0.5
See also
Open in the full glossarydocs.python.orgReport an inaccuracy