How to Calculate Variance in Python

If you need to calculate variance in Python, then you can do the following.

Option 1 – Using variance() from Statistics module

import statistics

list = [12,14,10,6,23,31]
print("List : " + str(list))

var = statistics.variance(list)
print("Variance: " + str(var))

Option 2 – Using var() from numpy module

import numpy as np

arr = [12,43,24,17,32]

print("Array : ", arr)
print("Variance: ", np.var(arr))

Option 3 – Using sum() and List Comprehensions

list = [12,43,24,17,32]
average = sum(list) / len(list)
var = sum((x-average)**2 for x in list) / len(list)
print(var)