Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Mean deviation of Elements
When finding the mean deviation (standard deviation) of elements in a list, Python's sum() and len() functions are commonly used. Mean deviation measures how spread out the values are from the average.
What is Mean Deviation?
Mean deviation, often called standard deviation, is calculated by:
- Finding the mean (average) of all values
- Computing the squared differences from the mean
- Taking the average of those squared differences
- Finding the square root of that average
Example
Below is a demonstration of calculating mean deviation ?
numbers = [3, 5, 7, 10, 12]
print("The list is :")
print(numbers)
# Calculate mean
mean = sum(numbers) / len(numbers)
# Calculate variance (average of squared differences)
variance = sum([((x - mean) ** 2) for x in numbers]) / len(numbers)
# Calculate standard deviation (square root of variance)
result = variance ** 0.5
print("The mean is :", mean)
print("The standard deviation is :", result)
Output
The list is : [3, 5, 7, 10, 12] The mean is : 7.4 The standard deviation is : 3.2619012860600183
Using Built-in Statistics Module
Python's statistics module provides a simpler approach ?
import statistics
numbers = [3, 5, 7, 10, 12]
print("The list is :", numbers)
print("Standard deviation using statistics.stdev():", statistics.stdev(numbers))
print("Population standard deviation:", statistics.pstdev(numbers))
The list is : [3, 5, 7, 10, 12] Standard deviation using statistics.stdev(): 3.5355339059327378 Population standard deviation: 3.2619012860600183
Key Differences
| Method | Divisor | Use Case |
|---|---|---|
| Manual calculation | n (population) | When you have the entire population |
statistics.stdev() |
n-1 (sample) | When working with sample data |
statistics.pstdev() |
n (population) | When you have the entire population |
Conclusion
Use the manual calculation for learning purposes or when you need custom variance calculations. For production code, prefer the statistics module which handles edge cases and provides both sample and population standard deviation.
Advertisements
