Python | List variance



Method # 1: Using Loop + Formula
An easier way to solve this problem — use the formula to find the variance and execute using shortened loops. This is the most basic approach for solving this problem.

# Python3 code to demonstrate how it works
# List variance
# using loop + formula

 
# initialize the list

test_list = [ 6 , 7 , 3 , 9 , 10 , 15 ]

 
#print original about the list

print ( "The original list is: " + str (test_list))

 
# List variance
# using loop + formula

mean = sum (test_list) / len (test_list)

res = sum ((i - mean) * * 2 for i in test_list) / len (test_list)

 
# print result

print ( "The variance of list is:" + str (res))

Output:

 The original list is: [6, 7, 3, 9, 10, 15] The variance of list is: 13.888888888888891 

Method # 2: Using statistics.variance ()
This task can also be accomplished using the built-in variance () function.

# Python3 code for de monster work
# List variance
# using statistics.variance

import statistics 

 
# initialize the list

test_list = [ 6 , 7 , 3 , 9 , 10 , 15 ]

  
# print the original list

print ( "The origin al list is: " + str (test_list))

 
# List variance
# using statistics.variance

res = statistics.variance (test_list)

  
# print result

print ( "The variance of list is:" + str (res))

Output:

 The original list is: [6, 7, 3 , 9, 10, 15] The variance of list is: 13.888888888888891