Python | Variance of List

While working with Python, we can have a problem in which we need to find variance of a list cumulative. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using loop + formula
The simpler manner to approach this problem is to employ the formula for finding variance and perform using loop shorthands. This is the most basic approach to solve this problem.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Variance of List
# using loop + formula
  
# initialize list
test_list = [6, 7, 3, 9, 10, 15]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Variance of List
# using loop + formula
mean = sum(test_list) / len(test_list)
res = sum((i - mean) ** 2 for i in test_list) / len(test_list)
  
# printing result
print("The variance of list is : " + str(res))

chevron_right


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 performed using inbuilt function of variance().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Variance of List
# using statistics.variance
import statistics 
  
# initialize list
test_list = [6, 7, 3, 9, 10, 15]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Variance of List
# using statistics.variance
res = statistics.variance(test_list)
  
# printing result
print("The variance of list is : " + str(res))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.