The mean() function from Python’s statistics module is used to calculate the arithmetic average of numeric values. It adds all the values and divides the sum by the total number of values. This function is commonly used to find the central value of data.
Example: This example calculates the average of numbers in a list using mean().
import statistics
d = [10, 20, 30, 40]
r = statistics.mean(d)
print(r)
Output
25
Explanation:
- d = [10, 20, 30, 40] creates a list of numbers.
- statistics.mean(d) adds all values and divides by total count.
Syntax
statistics.mean(data)
- Parameters: data - An iterable such as list, tuple or set containing numeric values.
- Return Value: Returns the arithmetic mean of the given data.
Examples
Example 1: This example finds the average marks of students stored in a list. It helps understand overall student performance.
import statistics
m = [85, 90, 78, 92, 88]
r = statistics.mean(m)
print("Mean:", r)
Output
Mean: 86.6
Example 2: This example calculates the mean of fraction values using the Fraction class. It shows that mean() returns the result as a fraction when all inputs are fractions.
from statistics import mean
from fractions import Fraction as fr
d = [fr(1, 2), fr(3, 4), fr(5, 6)]
r = mean(d)
print("Mean:", r)
Output
Mean: 25/36
Explanation:
- d = [fr(1, 2), fr(3, 4), fr(5, 6)] creates a list of fraction numbers.
- r = mean(d) adds all fractions and divides by total number of values.
Example 3: This example tries to calculate the mean of string values. Since mean() works only with numeric values, it raises a TypeError.
import statistics
d = ["a", "b", "c"]
r = statistics.mean(d)
print(r)
Output
TypeError: can't convert type 'str' to numerator/denominator