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.
If the data has fewer than two values, StatisticsError raises.
- data: This parameter is required when data is an array of valid Python numbers, including Decimal and Fraction values.
- 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)
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)
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)))
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))
statistics.StatisticsError: variance requires at least two data points