Python | Standard deviation of list
Last Updated :
28 Jan, 2024
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.
Python3
test_list = [ 4 , 5 , 8 , 9 , 10 ]
print ( "The original list : " + str (test_list))
mean = sum (test_list) / len (test_list)
variance = sum ([((x - mean) * * 2 ) for x in test_list]) / len (test_list)
res = variance * * 0.5
print ( "Standard deviation of sample is : " + str (res))
|
Output
The original list : [4, 5, 8, 9, 10]
Standard deviation of sample is : 2.3151673805580453
Time Complexity: O(n) where n is the number of elements in the list “test_list”. sum() + list comprehension performs n number of operations.
Auxiliary Space: O(1), constant extra space is required
Method #2 : Using pstdev() This task can also be performed using inbuilt functionality of pstdev(). This function computes standard deviation of sample internally.
Python3
import statistics
test_list = [ 4 , 5 , 8 , 9 , 10 ]
print ( "The original list : " + str (test_list))
res = statistics.pstdev(test_list)
print ( "Standard deviation of sample is : " + str (res))
|
Output
The original list : [4, 5, 8, 9, 10]
Standard deviation of sample is : 2.3151673805580453
Method #3 : Using numpy library
Note: Install numpy module using command “pip install numpy”
Another approach to calculate the standard deviation of a list is by using the numpy library. The numpy library provides a function called std() which can be used to calculate the standard deviation of a list.
Python3
import numpy as np
test_list = [ 4 , 5 , 8 , 9 , 10 ]
res = np.std(test_list)
print (res)
|
Output:
2.3151673805580453
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...