calculate the variance in python

There are several ways to calculate the variance in Python, some of them are:

Using the statistics module:

main.py
import statistics

data = [1, 2, 3, 4, 5]
variance = statistics.variance(data)
print(variance)
95 chars
6 lines

Using the numpy library:

main.py
import numpy as np

data = [1, 2, 3, 4, 5]
variance = np.var(data)
print(variance)
83 chars
6 lines

Using basic math calculations:

main.py
data = [1, 2, 3, 4, 5]
mean = sum(data) / len(data)
variance = sum((x - mean) ** 2 for x in data) / len(data)
print(variance)
126 chars
5 lines

All of the above methods should give the variance of the data, you can choose the method that suits your needs better.

gistlibby LogSnag