Calculating Mean, Median, Mode, and Range in Python
This tutorial will guide you through calculating the mean, median, mode, and range of a dataset using Python. We’ll build three progressively complex code examples to solidify your understanding.
Example 1: Basic Mean Calculation
Let’s start with calculating the mean (average) of a simple list of numbers. The mean is calculated by summing all the numbers in the list and dividing by the total number of elements.
def calculate_mean(data):
"""Calculates the mean of a list of numbers.
Args:
data: A list of numbers.
Returns:
The mean of the numbers in the list. Returns None if the list is empty.
"""
if not data:
return None # Handle empty list to avoid division by zero
total = sum(data)
mean = total / len(data)
return mean
# Example usage:
numbers = [10, 20, 30, 40, 50]
mean_value = calculate_mean(numbers)
if mean_value is not None:
print(f"The mean is: {mean_value}")
else:
print("The list is empty, cannot calculate the mean.")
Explanation:
- We define a function called `calculate_mean` that takes a list of numbers (`data`) as input.
- Inside the function, we check if the list is empty. If it is, we return `None` to avoid a `ZeroDivisionError`. This is a crucial best practice for handling potential errors.
- We calculate the sum of the numbers in the list using the `sum()` function.
- We calculate the mean by dividing the total sum by the number of elements in the list (obtained using `len()`).
- Finally, we return the calculated mean.
We then demonstrate the usage of the function with a sample dataset and print the result.
numbers = [10, 20, 30, 40, 50]
mean_value = calculate_mean(numbers)
if mean_value is not None:
print(f"The mean is: {mean_value}")
else:
print("The list is empty, cannot calculate the mean.")
Output:
The mean is: 30.0
Example 2: Calculating Median and Range
Now, let’s calculate the median and range. The median is the middle value in a sorted dataset, while the range is the difference between the maximum and minimum values.
def calculate_median(data):
"""Calculates the median of a list of numbers.
Args:
data: A list of numbers.
Returns:
The median of the numbers in the list. Returns None if the list is empty.
"""
if not data:
return None
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 0: # Even number of elements
mid1 = sorted_data[n // 2 - 1]
mid2 = sorted_data[n // 2]
median = (mid1 + mid2) / 2
else: # Odd number of elements
median = sorted_data[n // 2]
return median
def calculate_range(data):
"""Calculates the range of a list of numbers.
Args:
data: A list of numbers.
Returns:
The range of the numbers in the list. Returns None if the list is empty.
"""
if not data:
return None
minimum = min(data)
maximum = max(data)
range_value = maximum - minimum
return range_value
# Example usage:
numbers = [10, 20, 30, 40, 50, 60]
median_value = calculate_median(numbers)
range_value = calculate_range(numbers)
if median_value is not None:
print(f"The median is: {median_value}")
else:
print("The list is empty, cannot calculate the median.")
if range_value is not None:
print(f"The range is: {range_value}")
else:
print("The list is empty, cannot calculate the range.")
Explanation:
- The `calculate_median` function sorts the input list and then calculates the median based on whether the list has an even or odd number of elements.
- The `calculate_range` function finds the minimum and maximum values in the list and returns their difference.
The median is: 35.0
The range is: 50
Example 3: Handling Edge Cases and Input Validation
Let’s enhance our code to handle edge cases and potential input errors more robustly. We’ll add input validation to ensure the input list contains only numbers.
def calculate_stats(data):
"""Calculates mean, median, mode, and range of a list of numbers.
Args:
data: A list of numbers.
Returns:
A dictionary containing the mean, median, mode, and range, or None if the list is empty or contains invalid data.
"""
if not data:
print("Error: Input list is empty.")
return None
try:
data = [float(x) for x in data] # Convert to float, handles strings as input
except ValueError:
print("Error: Input list contains non-numeric values.")
return None
# Calculate mean
mean = sum(data) / len(data)
# Calculate median
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 0:
median = (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2
else:
median = sorted_data[n // 2]
# Calculate range
range_value = max(data) - min(data)
# Calculate mode (simple implementation - assumes one mode)
counts = {}
for x in data:
counts[x] = counts.get(x, 0) + 1
mode = max(counts, key=counts.get)
return {
"mean": mean,
"median": median,
"mode": mode,
"range": range_value
}
# Example usage:
data = [10, 20, 30, 20, 40, 50, 20]
stats = calculate_stats(data)
if stats:
print(stats)
Explanation:
- The `calculate_stats` function now includes a `try-except` block to catch `ValueError` if the input list contains non-numeric values.
- The input list is converted to a list of floats using a list comprehension, allowing input as strings that can be converted to numbers.
- The mode calculation is implemented using a dictionary to count the occurrences of each number.
{'mean': 27.142857142857142, 'median': 20.0, 'mode': 20, 'range': 40}



Leave a Reply