How to Calculate Variance in Python

0 min read 87 words

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)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags