Python | Standard deviation of list

Sometimes, while working with Mathematics, we can have a problem in which we intend to compute the standard deviation of a sample. This has many applications in competitive programming as well as school level projects. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using sum() + list comprehension
This is a brute force shorthand to perform this particular task. We can approach this problem in sections, computing mean, variance and standard deviation as square root of variance. The sum() is key to compute mean and variance. List comprehension is used to extend the common functionality to each of element of list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Standard deviation of list
# Using sum() + list comprehension
  
# initializing list
test_list = [4, 5, 8, 9, 10]
  
# printing list
print("The original list : " + str(test_list))
  
# Standard deviation of list
# Using sum() + list comprehension
mean = sum(test_list) / len(test_list)
variance = sum([((x - mean) ** 2) for x in test_list]) / len(test_list)
res = variance ** 0.5
  
# Printing result
print("Standard deviation of sample is : " + str(res))

chevron_right


Output :



 
The original list : [4, 5, 8, 9, 10]
Standard deviation of sample is : 2.3151673805580453

Method #2 : Using pstdev()
This task can also be performed using inbuilt functionality of pstdev(). This function computes standard deviation of sample internally.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Standard deviation of list
# Using pstdev()
import statistics
  
# initializing list
test_list = [4, 5, 8, 9, 10]
  
# printing list
print("The original list : " + str(test_list))
  
# Standard deviation of list
# Using pstdev()
res = statistics.pstdev(test_list)
  
# Printing result
print("Standard deviation of sample is : " + str(res))

chevron_right


Output :

 
The original list : [4, 5, 8, 9, 10]
Standard deviation of sample is : 2.3151673805580453


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.