Calculate Mean, Median, Mode in Python: Simple Guide
You can calculate
mean, median, and mode in Python using the statistics module. Use statistics.mean() for average, statistics.median() for the middle value, and statistics.mode() for the most common value in a list of numbers.Syntax
Use the statistics module functions with a list of numbers:
statistics.mean(data): Returns the average of the numbers.statistics.median(data): Returns the middle value when data is sorted.statistics.mode(data): Returns the most frequent value.
python
import statistics data = [1, 2, 3, 4, 5] mean_value = statistics.mean(data) median_value = statistics.median(data) mode_value = statistics.mode(data)
Example
This example shows how to calculate mean, median, and mode for a list of numbers.
python
import statistics data = [2, 3, 5, 3, 7, 3, 9] mean_value = statistics.mean(data) median_value = statistics.median(data) mode_value = statistics.mode(data) print(f"Mean: {mean_value}") print(f"Median: {median_value}") print(f"Mode: {mode_value}")
Output
Mean: 4.571428571428571
Median: 3
Mode: 3
Common Pitfalls
Common mistakes include:
- Using
mode()on data with multiple modes causes an error. - Passing empty lists causes errors.
- Not importing the
statisticsmodule.
To handle multiple modes, use statistics.multimode() instead.
python
import statistics data = [1, 2, 2, 3, 3] # Wrong: mode() will raise an error if multiple modes exist # mode_value = statistics.mode(data) # This raises StatisticsError # Right: use multimode() to get all modes mode_values = statistics.multimode(data) print(f"Modes: {mode_values}")
Output
Modes: [2, 3]
Quick Reference
| Function | Purpose | Input | Output |
|---|---|---|---|
| statistics.mean(data) | Calculate average | List of numbers | Float |
| statistics.median(data) | Find middle value | List of numbers | Number |
| statistics.mode(data) | Find most common value | List of numbers | Single value |
| statistics.multimode(data) | Find all modes | List of numbers | List of values |
Key Takeaways
Use the statistics module to easily calculate mean, median, and mode in Python.
Mean is the average, median is the middle value, and mode is the most frequent value.
Use statistics.multimode() to handle multiple modes safely.
Always provide a non-empty list of numbers to avoid errors.
Import the statistics module before using its functions.