Python statistics.mean() is a built-in method that calculates the sample arithmetic mean (commonly known as the “average”) of input numeric data. The numeric data can be anything from numbers, lists, dictionaries, sets, or tuples.
The basic formula to calculate the arithmetic average is: sum(data) / len(data)
To calculate the average of a list, pass the list to the statistics.mean() method. It returns the average of the whole list. Underneath, it calculates the sum of all elements and divides it by the total number of elements.
import statistics main_list = [1, 1, 2, 2, 3] mean_of_list = statistics.mean(main_list) print(mean_of_list) # Output: 1.8
Syntax
mean(input)
Parameters
Argument | Description |
input |
It represents a non-empty iterable (e.g., list, tuple, range, or generator) containing real-valued numbers. It includes int, float, fractions.Fraction, and decimal.Decimal |
Exceptions
The mean() function may throw a TypeError exception when anything other than numeric values is passed as an argument. It may raise StatisticsError error if the data is empty.
List of negative integers
What if the input list contains negative integers? Well, it still works the same. It first calculates the sum of all elements and divides it by the number of elements.
import statistics negative_list = [-11, -21, -18, -19, -46] mean_of_negative_list = statistics.mean(negative_list) print(mean_of_negative_list) # Output: -23
Let’s consider a list that includes a mixed range of numbers.
import statistics mixed_list = [11, 21, -18, -19, 46] print(statistics.mean(mixed_list)) # Output: 8.2
Mean of the dictionary
If the input is a dictionary, it only counts keys as elements to calculate the mean of it.
In Python, dictionary keys must be unique. If a dictionary is defined with duplicate keys, only the last assignment is kept.
import statistics main_dict = {1: 19, 2: 18, 3: 46, 4: 30} mean_of_dict = statistics.mean(main_dict) print(mean_of_dict) # Output: 2.5 (1 + 2 + 3 + 4) / 4
The keys in the dictionary are 1, 2, 3, 4, and their mean is 2.5.
Mean of a tuple
It does not matter if the numbers in a tuple are positive or negative. It should be a real number.
Let’s define a tuple with negative integers and calculate its mean.
import statistics negative_tuple = (-11, -21, -18, -19, -46) mean_of_negative_tuple = statistics.mean(negative_tuple) print(mean_of_negative_tuple) # Output: -23.0
Let’s consider a tuple containing a mixed range of numbers.
import statistics mixed_tuple = (11, 21, -18, 19, -46) print(statistics.mean(mixed_tuple)) # Output: -2.6
Mean with decimal (High Precision)
For high-precision decimal values, we can utilize the built-in Decimal module to create a list of highly decimal values and calculate their mean.
from statistics import mean from decimal import Decimal data = [Decimal("0.3"), Decimal("0.6"), Decimal("0.1")] print(mean(data)) # Output: 0.3333333333333333333333333333
Mean with Fraction (Exact Rational Arithmetic)
The Fraction class (from Python’s fractions module) represents rational numbers exactly, as a numerator/denominator pair.
- Fraction(1, 4) → 1 / 4
- Fraction(1, 2) → 1 / 2
- Fraction(3, 4) → 3 / 4
from fractions import Fraction from statistics import mean data = [Fraction(1, 4), Fraction(1, 2), Fraction(3, 4)] print(mean(data)) # Output: 1/2
From the above output, you can see that since the input was a list of Fraction objects, statistics.mean() preserves the type and returns another Fraction, not a float.
Empty Data (Edge Case)
If your input list is empty and you attempt to find its mean, it will throw statistics.StatisticsError: mean requires at least one data point
However, we can handle it using the try/except mechanism.
import statistics empty_list = [] try: print(statistics.mean(empty_list)) except statistics.StatisticsError as e: print(e) # Output: mean requires at least one data point
Ensures at least one data point; prevents division by zero.
TypeError: can’t convert type ‘str’ to numerator/denominator
Let’s say we have a dictionary with keys that are characters, not integers. If you directly pass the dictionary to the mean() function, it will throw TypeError: can’t convert type ‘str’ to numerator/denominator because the keys are characters, not valid numbers.
import statistics data = {"a": 11, "b": 21, "c": 19, "d": 29, "e": 18} print(statistics.mean(data)) # Error: TypeError: can't convert type 'str' to numerator/denominator
We encountered a TypeError because statistics.mean() requires an iterable of numbers, whereas we provided an entire dictionary of data instead of just its values.
To fix this TypeError, the correct approach is to extract the values from the dictionary using dict.values() function and then calculate the mean.
import statistics data = {"a": 11, "b": 21, "c": 19, "d": 29, "e": 18} # Extract the values from the dictionary and calculate the mean mean_of_values = statistics.mean(data.values()) print(mean_of_values) # Output: 19.6
That’s all!
הובלות
many thanks a good deal this website is actually professional and simple
joshua
well explained