Open In App

statistics mean() function – Python

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The mean() function from Python’s statistics module is used to calculate the average of a set of numeric values. It adds up all the values in a list and divides the total by the number of elements.

For example, if we have a list [2, 4, 6, 8], the mean would be (2 + 4 + 6 + 8) / 4 = 5.0. This function is useful when analyzing data and finding central tendencies. 

Syntax of mean()

statistics.mean(data)

Parameters : 

  • data: A list, tuple, or iterable of numeric values.

Return Type: Arithmetic mean of the provided data-set.

Raises: TypeError if any non-numeric values are present. 

Examples of mean() Function

Example 1: Simple List of Numbers

Python
import statistics

d1 = [1, 3, 4, 5, 7, 9, 2]
print("Mean:", statistics.mean(d1))

Output
Mean: 4.428571428571429

Example 2: Tuples, Negative Numbers and Fractions

Python
from statistics import mean
from fractions import Fraction as fr

d1 = (11, 3, 4, 5, 7, 9, 2)
d2 = (-1, -2, -4, -7, -12, -19)
d3 = (-1, -13, -6, 4, 5, 19, 9)
d4 = (fr(1, 2), fr(44, 12), fr(10, 3), fr(2, 3))
d5 = {1: "one", 2: "two", 3: "three"}  # Only keys are used

print("Mean d1:", mean(d1))
print("Mean d2:", mean(d2))
print("Mean d3:", mean(d3))
print("Mean d4:", mean(d4))
print("Mean d5:", mean(d5))

Output
Mean d1: 5.857142857142857
Mean d2: -7.5
Mean d3: 2.4285714285714284
Mean d4: 49/24
Mean d5: 2

Explanation:

  • For Fraction inputs (fr()), the result is a Fraction.
  • For dictionaries, mean() considers only the keys, not the values.

Example 3: TypeError When Using Invalid Types

Python
from statistics import mean

d = {"one": 1, "three": 3, "seven": 7, "twenty": 20, "nine": 9, "six": 6}
print(mean(d))  # Raises TypeError

Output : 

Hangup (SIGHUP)
Traceback (most recent call last):
File “/usr/local/lib/python3.13/statistics.py”, line 331, in _exact_ratio
return (x.numerator, x.denominator)
^^^^^^^^^^^
AttributeError: ‘str’ object has no attribute ‘numerator’

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “/home/guest/sandbox/Solution.py”, line 4, in <module>
print(mean(d)) # Raises TypeError

Explanation: In the above code, the dictionary keys are strings, so mean() throws a TypeError.

Applications

The mean() function is a key statistical tool when working with:

  • Data science
  • Machine learning
  • Trend analysis
  • Summarizing large datasets

It’s used to find the central tendency or typical value in a collection of numbers.

Prerequisite : Introduction to Statistical Functions



Next Article

Similar Reads