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:
Where:
= variance
= value of one observation
= the mean value of the data
= 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 setdata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# to obtain the variancethe_variance = statistics.variance(data)print('The variance is', the_variance)
Explanation
- Line 1: We import the
statisticsmodule. - Line 4: We create a data set called
data. - Line 6: We use the
statistics.variance()method to obtain the variance of thedataand assign the value to another variable,the_variance. - Line 7: We print
the_variance, which contains the variance of the given data.