We use the covariance()
method in Python to get the sample covariance of two inputs.
Covariance is a measure of the directional relationship between two random variables in statistics. The covariance between two random variables can have the following values:
When we use the covariance()
method, the length of both the inputs has to be the same.
This method was introduced in Python version 3.10.
covariance(x, y, /)
x
: It is the first input.y
: It is the second input.The method returns the covariance value.
import statisticsx = [2, 3, 4, 2]y = [3, 5, 9, 0]print("Covariance - ", statistics.covariance(x, y))
statistics
module.x
.y
.covariance()
method.Here, the covariance value is positive. This indicates that both the random variables/inputs move in the same direction.
import statisticsx = [2, 3, 4, 2]y = [1, -1, -2, 0]print("Covariance - ", statistics.covariance(x, y))
statistics
module.x
.y
.covariance()
method.Here, the covariance value is negative. This indicates that both the random variables/inputs move in the opposite direction.