The statistics.mean
function in Python's statistics
module is used to calculate the arithmetic mean (average) of a given set of numbers. This function is useful for finding the central value of a dataset.
Table of Contents
- Introduction
statistics.mean
Function Syntax- Examples
- Basic Usage
- Mean of a List of Numbers
- Mean of a Tuple of Numbers
- Handling Different Types of Numeric Data
- Real-World Use Case
- Conclusion
Introduction
The statistics.mean
function is part of the statistics
module, which provides functions for mathematical statistics of numeric data. The mean is the sum of the data divided by the number of data points.
statistics.mean Function Syntax
Here's how you use the statistics.mean
function:
import statistics
mean_value = statistics.mean(data)
Parameters:
data
: A sequence or iterable of numeric data (list, tuple, etc.).
Returns:
- The arithmetic mean of the given data.
Raises:
StatisticsError
: Ifdata
is empty.
Examples
Basic Usage
Calculate the mean of a list of numbers.
import statistics
data = [1, 2, 3, 4, 5]
mean_value = statistics.mean(data)
print(f"Mean: {mean_value}")
Output:
Mean: 3
Mean of a List of Numbers
Calculate the mean of a list of integers.
import statistics
numbers = [10, 20, 30, 40, 50]
mean_value = statistics.mean(numbers)
print(f"Mean of numbers: {mean_value}")
Output:
Mean of numbers: 30
Mean of a Tuple of Numbers
Calculate the mean of a tuple of floats.
import statistics
numbers = (1.5, 2.5, 3.5, 4.5, 5.5)
mean_value = statistics.mean(numbers)
print(f"Mean of numbers: {mean_value}")
Output:
Mean of numbers: 3.5
Handling Different Types of Numeric Data
Calculate the mean of a mixed list of integers and floats.
import statistics
numbers = [1, 2.5, 3, 4.5, 5]
mean_value = statistics.mean(numbers)
print(f"Mean of numbers: {mean_value}")
Output:
Mean of numbers: 3.2
Real-World Use Case
Calculating the Average Score
Calculate the average score of students in a class.
import statistics
scores = [85, 90, 78, 92, 88, 76, 95, 89]
average_score = statistics.mean(scores)
print(f"Average score: {average_score}")
Output:
Average score: 86.625
Conclusion
The statistics.mean
function is a simple and effective way to calculate the arithmetic mean of a set of numbers in Python. It can handle different types of numeric data and is useful in various real-world scenarios where calculating the average is needed. This function makes it easy to find the central value of a dataset, which is a common requirement in data analysis and statistics.
Comments
Post a Comment
Leave Comment