Python statistics.variance() Method

Python statistics.variance() method is “used to calculate the variance of a sample dataset.” A variance measures the spread of a dataset and is calculated as the average of the squared differences between each data point and the mean of the dataset.

Syntax

statistics.variance(data, xbar=None)

If the data has fewer than two values, StatisticsError raises.

Parameters

  1. data: This parameter is required when data is an array of valid Python numbers, including Decimal and Fraction values.
  2. xbar: Where xbar is the mean of data, this parameter is optional. The mean is automatically calculated if this parameter is not given(none).

Example 1: How to Use statistics.variance() Method

import statistics

dataset = [21, 19, 11, 21, 19, 46, 29]
output = statistics.variance(dataset) 

print(output)

Output

124.23809523809524

Example 2

Calculate the mean first and pass it to the variance() method as an argument.

import statistics

dataset = [21, 19, 11, 21, 19, 46, 29]
meanValue = statistics.mean(dataset)
output = statistics.variance(dataset, meanValue) 

print(output)

Output

124.23809523809524 

Example 3: Use of xbar parameter in statistics.variance() method

import statistics

# creating a sample list
sample = (1.1, 1.2, 1.9, 2.1, 1.8, 2.2)

# calculating the mean of sample set
mean = statistics.mean(sample)

# calculating the variance of sample set
print("Variance of Sample set is % s"
 % (statistics.variance(sample, xbar=mean)))

Output

Variance of Sample set is 0.2136666666666667

Example 4: statistics.StatisticsError: variance requires at least two data points

import statistics

# creating a sample list
sample = []

print(statistics.variance(sample))

Output

statistics.StatisticsError: variance requires at least two data points

That’s it.

See also

Python mean()

Python mode()

Python median()

Python stddev()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.