How to Calculate the Mean, Median, and Mode of a List of Numbers
How to Calculate the Mean, Median, and Mode of a List of Numbers
How to Calculate the Mean, Median, and Mode of a List of Numbers
I have a list of numbers and I need to calculate their mean, median, and mode. How can I do this?
solveurit24@gmail.com Changed status to publish February 16, 2025
The mean is the average, the median is the middle value, and the mode is the most frequent value.
Code Example:
def calculate_stats(numbers):
mean = sum(numbers) / len(numbers)
sorted_numbers = sorted(numbers)
n = len(sorted_numbers)
median = (sorted_numbers[n//2] + sorted_numbers[(n-1)//2]) / 2
frequency = {}
for num in numbers:
frequency[num] = frequency.get(num, 0) + 1
mode = max(frequency, key=lambda k: frequency[k])
return mean, median, mode
# Example usage
data = [1, 2, 3, 4, 5, 5]
print(calculate_stats(data)) # Output: (3.5, 3.5, 5)This function calculates the mean, median, and mode of a list of numbers and returns them.
solveurit24@gmail.com Changed status to publish February 16, 2025