Python statistics mean() Function
The Python statistics.mean() function calculates the mean of the given data set. Data set is passed as a parameter where this can be used to calculate the average of a given list.
Mean is commonly called as the average sum of the arithmetic mean that is divided by the number of data points.
If this function contains empty dataset then statisticsError will be raised.
Syntax
Following is the basic syntax of the statistics.mean() function −
statistics.mean(data)
Parameters
Here, the data values can be used as any sequence, list or iterator.
Return Value
This function returns the arithmetic mean of data which can be a sequence or iterator.
Example 1
In the below example we are calculating the average of the given data using statistics.mean function.
import statistics print(statistics.mean([5, 10, 15, 20, 25])) print(statistics.mean([-11, 4.8, -2, 23]))
Output
The output obtained is as follows −
15 3.7
Example 2
Here, we are importing fractions to find the mean of the given data using statistics.mean() function.
import statistics from fractions import Fraction as F x = statistics.mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)]) print(x)
Output
When we run the above code we will get the following output −
13/21
Example 3
Now, we are passing decimal values to find the mean of the given data using statistics.mean() function.
import statistics
from decimal import Decimal as D
x = statistics.mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
print(x)
Output
The result is obtained as follows −
0.5625
Example 4
If we don't pass any data point as a parameter to this function, then it will throw StatisticsError as shown in the below example.
import statistics # creating an empty population set pop = () # will raise StatisticsError print(statistics.pvariance(pop))
Output
While executing the above code we will get the following error −
Traceback (most recent call last):
File "/home/cg/root/50576/main.py", line 7, in <module>
print(statistics.pvariance(pop))
File "/usr/lib/python3.10/statistics.py", line 811, in pvariance
raise StatisticsError('pvariance requires at least one data point')
statistics.StatisticsError: pvariance requires at least one data point