What is the statistics variance() method in Python?

Overview

The statistics.variance() method in Python is used to return the variance of a sample of given data.

This method is unlike the statistics.pvariance() method, which calculates the variance of an entire population.

Variance is the sum of the squared distances of each term distribution from the mean of the data, divided by the number of observations, is shown below:

S2=(xixˉ)2n1S^2 = \frac{\sum (x_i - \bar{x})^2}{n - 1}

Where:

S2S^{2} = variance

xixi = value of one observation

xx = the mean value of the data

nn = the number of observations

Syntax

statistics.variance(data, xbar)

Parameter value

Parameter Value
data It is required with real-valued numbers. It can be a list, a sequence, or an iterator.
xbar It is required and iterable with real-valued numbers. It can be a list or a sequence.

Return value

The statistics.variance() method returns a float value, which represents the variance of the given data.

Example

Let’s use the statistics.variance() method to calculate the variance for the given data.

Code

import statistics
# creating a data set
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# to obtain the variance
the_variance = statistics.variance(data)
print('The variance is', the_variance)

Explanation

  • Line 1: We import the statistics module.
  • Line 4: We create a data set called data.
  • Line 6: We use the statistics.variance() method to obtain the variance of the data and assign the value to another variable, the_variance.
  • Line 7: We print the_variance, which contains the variance of the given data.

Free Resources