0
0
Data-analysis-pythonHow-ToBeginner ยท 3 min read

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 statistics module.

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

FunctionPurposeInputOutput
statistics.mean(data)Calculate averageList of numbersFloat
statistics.median(data)Find middle valueList of numbersNumber
statistics.mode(data)Find most common valueList of numbersSingle value
statistics.multimode(data)Find all modesList of numbersList 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.