Python 3.10+statisticsfunction
statistics.covariance
relationships
Sample covariance of two datasets (3.10+).
Syntax
statistics.covariance(x, y)
The value carries the units of both inputs — switch metres to centimetres and it grows a hundredfold — so it is useless for comparing the strength of relationships; correlation is the tool for that, while covariance is mostly read for its sign. Zero means no linear relationship rather than independence, and both inputs must be the same length with at least two values.
Examples
import statistics
print(statistics.covariance([1, 2, 3], [2, 4, 6])) # → 2.0
print(statistics.covariance([1, 2, 3], [6, 4, 2])) # → -2.0
print(statistics.covariance([1, 2, 3, 4], [1, 2, 2, 1])) # → 0.0
print(statistics.covariance([1, 2, 3], [1, 2, 3]) == statistics.variance([1, 2, 3])) # → True
print(statistics.covariance([1, 2, 3], [1, 2])) # → StatisticsError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy