YouTip LogoYouTip

Ref Stat Mean

## Python statistics.mean() Method The `statistics.mean()` method is a built-in function in Python's standard library `statistics` module. It is used to calculate the arithmetic mean (average) of a given sequence or dataset. The arithmetic mean is the sum of all data points divided by the total number of data points. It is a fundamental measure of central tendency used to describe the center of a distribution. --- ### Syntax ```python statistics.mean(data) ``` #### Parameters * **`data`**: An iterable containing numeric data types (such as `list`, `tuple`, or `range`). The elements can be integers, floats, decimals, or fractions. #### Return Value * Returns the calculated arithmetic mean as a float (or a `Decimal` / `Fraction` if the input data contains those specific types). --- ### Code Examples #### Example 1: Basic Usage with a List of Integers This example demonstrates how to calculate the mean of a simple list of integers. ```python import statistics # Define a dataset data = [1, 2, 3, 4, 5] # Calculate the arithmetic mean mean_value = statistics.mean(data) print(f"The mean is: {mean_value}") ``` **Output:** ```text The mean is: 3.0 ``` #### Example 2: Working with Floating-Point Numbers The method handles floating-point numbers seamlessly. ```python import statistics # Dataset with floats data = [1.5, 2.5, 3.75, 4.25] mean_value = statistics.mean(data) print(f"The mean is: {mean_value}") ``` **Output:** ```text The mean is: 3.0 ``` #### Example 3: Using Decimal and Fraction Types For high-precision financial or mathematical calculations, you can pass `decimal.Decimal` or `fractions.Fraction` objects. ```python import statistics from decimal import Decimal from fractions import Fraction # Using Decimal for high precision decimal_data = [Decimal("0.1"), Decimal("0.2"), Decimal("0.3")] print("Decimal Mean:", statistics.mean(decimal_data)) # Using Fraction to avoid floating-point approximation errors fraction_data = [Fraction(1, 3), Fraction(1, 6), Fraction(1, 2)] print("Fraction Mean:", statistics.mean(fraction_data)) ``` **Output:** ```text Decimal Mean: 0.2 Fraction Mean: 1/3 ``` --- ### Considerations and Exceptions When using `statistics.mean()`, keep the following points in mind: 1. **Empty Datasets**: If the `data` parameter is empty, the method will raise a `StatisticsError`. ```python import statistics try: statistics.mean([]) except statistics.StatisticsError as e: print(f"Error: {e}") # Output: Error: mean requires at least one data point ``` 2. **Non-Numeric Data**: All elements in the iterable must be numeric. Passing strings or other non-numeric types will result in a `TypeError`. 3. **Performance**: For extremely large datasets or high-performance scientific computing, consider using the `numpy.mean()` function from the NumPy library, which is optimized for multi-dimensional arrays and performance.
← Ref Stat Median_GroupedPython Statistics β†’