What is the statistics.covariance() method in Python?

Overview

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:

  1. Positive: A positive covariance value suggests that both random variables move in the same direction. If one random variable increases, the other random variable also increases. Similarly, if one random variable decreases, the other also decreases.
  2. Negative: A negative covariance value suggests that both random variables move in the opposite direction. If one random variable increases, then the other random variable decreases. Similarly, if one random variable decreases, the other increases.
  3. Zero: When the two random variables are independent of each other, the covariance between them is zero.

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.

Syntax

covariance(x, y, /)

Parameters

  • x: It is the first input.
  • y: It is the second input.

Return value

The method returns the covariance value.

Example 1

import statistics
x = [2, 3, 4, 2]
y = [3, 5, 9, 0]
print("Covariance - ", statistics.covariance(x, y))

Explanation

  • Line 1: We import the statistics module.
  • Line 3: We define the first input x.
  • Line 4: We define the second input y.
  • Line 6: We calculate the covariance of the inputs using the covariance() method.

Here, the covariance value is positive. This indicates that both the random variables/inputs move in the same direction.

Example 2

import statistics
x = [2, 3, 4, 2]
y = [1, -1, -2, 0]
print("Covariance - ", statistics.covariance(x, y))

Explanation

  • Line 1: We import the statistics module.
  • Line 3: We define the first input x.
  • Line 4: We define the second input y.
  • Line 6: We calculate the covariance of the inputs using the covariance() method.

Here, the covariance value is negative. This indicates that both the random variables/inputs move in the opposite direction.

Free Resources