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**

**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)
```

**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**

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.