3 Easy Methods To Compute Variance Of Lists Using Python

Variance of lists in Python

In this tutorial, we will look at various ways for calculating the variance of lists in Python.


Methods to Calculate Variance of Lists In Python

Before we dive into the methods to calculate the variance of lists, let’s understand what variance means.

Variance is a crucial mathematical tool in statistics. It’s used to deal with massive volumes of data. For a given data collection, it is the square of the standard deviation.

Variance is also known as a distribution’s second central moment. The mean of the square minus the square of the mean of a given data set is used to compute it.

Variable (X) = E[(X- )2]


Method 1: Python variance function

Python includes a built-in function for computing the variance of lists. The syntax, as well as an explanation of its arguments, is provided below.

variance( [data], mean )

[data]: It provides a list of the data for which the variance is to be computed.
mean: It is a non-mandatory parameter. It uses the actual mean’s value.


Method 2: The Rudimentary method

This is the most basic way of computing the variance of lists. In the following example, we compute the mean and subsequently the variance using the above-mentioned formula.

We are not using any of the built-in methods here and instead calculating the variance of lists manually by building out the formula.

l = [1, 2, 3, 4, 5, 6] 
print("The original list is : " + str(l)) 
length= int(len(l))
mean = sum(l) / length 
ans = sum((i - mean) ** 2 for i in l) / length
print("The variance of list is : " + str(ans)) 

The output of the code is as follows:

The original list is : [1, 2, 3, 4, 5, 6]
The variance of list is : 2.9166666666666665

Method 3: Using statistics Module

In this example, we utilize the built-in function variance() which makes calculating the variance of lists very easy.

import statistics  
list1 = [1, 2, 3, 4, 5, 6] 
print("The original list is : " + str(list1)) 
ans = statistics.variance(list1) 
print("The variance of list is : " + str(ans)) 

The output of the code is as follows:

The original list is : [1, 2, 3, 4, 5, 6]
The variance of list is : 3.5

Conclusion

Congratulations! You just learned three different ways to compute the variance of a list using the Python programming language. Hope you enjoyed it! 😇

Liked the tutorial? I would recommend you to have a look at the tutorials mentioned below:

  1. Compute a^n in Python: Different Ways to Calculate Power in Python
  2. How to Compute Distance in Python? [ Easy Step-By-Step Guide ]

Thank you for taking your time out! Hope you learned something new!! 😄