01-Nov-2022
.
Admin
Hi Dev,
This article is focused on How to Get the Variance of a List in Python. This article goes in detailed on Python calculate variance without numpy. I explained simply step by step Find Variance Using Python Example. In this article, we will implement a Python Program to Calculate the Variance. Follow bellow tutorial step of NumPy Variance Function in Python.
Python program to find variance; In this tutorial, you will learn how to find or calculate the variance in python using numpy.
so let's see following examples with output:
Example 1: Write a program to calculate variance in python
import numpy as np
dataset= [21, 11, 19, 18, 29, 46]
variance= np.var(dataset)
print(variance)
Output:
124.66666666666667
Example 2: Python calculate variance without numpy
#define a function, to calculate variance
def variance(X):
mean = sum(X)/len(X)
tot = 0.0
for x in X:
tot = tot + (x - mean)**2
return tot/len(X)
# call the function with data set
x = [1, 2, 3, 4, 5, 6, 7, 8]
print("variance is: ", variance(x))
y = [1, 2, 3, -4, -5, -6, -7]
print("variance is: ", variance(y))
z = [10, -20, 30, -40, 50, -60, 70]
print("variance is: ", variance(z))
Output:
variance is: 5.25
variance is: 14.775510204081632
variance is: 1967.3469387755104
I hope it can help you...
#Python