Python mean() Function: Syntax and 6 Examples

If you want the average of a list of numbers in Python, the Python mean function does exactly that. It takes your list and gives you back the average, and you import it from the statistics module.

from statistics import mean
print(mean([42, 38, 51, 47, 45]))
# 44.6

In this tutorial, I’ll walk through mean() with six examples: lists, USD invoices, dictionaries, Decimal, weighted fmean() and the pandas/NumPy .mean() method. Outputs come from Python 3.12.5 in VS Code.

Python statistics.mean() Syntax

statistics.mean(data)
ParameterRequiredDefaultDescription
dataYes–A list, tuple or any iterable of numbers

Return value: the arithmetic mean. Its type follows the data: int, float, Decimal or Fraction.

Here’s how to use mean in Python: import it, or call statistics.mean() after import statistics. Nothing to install, and it takes one iterable, like the Python sum() function.

Note: an empty list raises StatisticsError, a subclass of ValueError.

When to Use mean() in Python

  • Average order size, invoice or price
  • Average sensor or temperature readings
  • Exact averages of Decimal money values
  • Quick stats before reaching for pandas

When you need to calculate the mean in Python without extra libraries, mean() is the cleanest choice. For other ways to average a list, see how to find the average of a list in Python.

Example 1: Calculate the Mean of a List in Python

Let me start with a week of daily orders:

from statistics import mean

daily_orders = [42, 38, 51, 47, 45]
print(mean(daily_orders))

print(mean([40, 50, 60]))
print(mean([19.99, 24.50, 9.75]))

Output:

44.6
50
18.08
Python mean function returning the average of daily orders, an int result and a float result in VS Code
mean() keeps the type when it can.

How does this work? 223 orders over 5 days gave 44.6. [40, 50, 60] averaged to exactly 50, so you got the int 50, not 50.0.

Example 2: Find the Average of USD Invoices in Python

Now some client invoices in dollars:

from statistics import mean

invoices = [1250.00, 980.50, 1499.99, 760.25, 2100.00]

avg = mean(invoices)
print(f"Average invoice: ${avg:,.2f}")

print(sum(invoices) / len(invoices))
print(sum(invoices) // len(invoices))

Output:

Average invoice: $1,318.15
1318.148
1318.0
Python mean of USD invoice amounts formatted as dollars next to sum divided by len in VS Code
mean() vs sum() / len().

How does this work? mean() returned 1318.148, which the f-string showed as $1,318.15. Dividing by len() matched, but // dropped the cents.

Pro Tip: use /, not //, for averages. See normal division vs floor division in Python.

Example 3: Mean of Dictionary Values and Generators

mean() accepts any iterable, not just lists. Here are November highs for five US cities:

from statistics import mean

highs_f = {"Phoenix": 74, "Chicago": 41, "Miami": 79,
           "Seattle": 50, "Denver": 48}

print(mean(highs_f.values()))
print(mean(t for t in highs_f.values() if t >= 50))

Output:

58.4
67.66666666666667

How does this work? highs_f.values() averaged to 58.4. The generator kept only cities at 50 or above, so you don’t need a temporary list.

Example 4: Get an Exact Mean with Decimal and Fraction

Money math in floats can drift, so I keep prices as Decimal:

from statistics import mean
from decimal import Decimal
from fractions import Fraction

prices = [Decimal("19.99"), Decimal("4.99"), Decimal("12.50")]
print(mean(prices))

print(mean([Fraction(1, 3), Fraction(1, 6), Fraction(1, 2)]))

Output:

12.49333333333333333333333333
1/3

How does this work? You get a Decimal back from a Decimal list, and the fractions gave exactly 1/3.

Example 5: Weighted Average with fmean() and Outliers

fmean() always returns a float, runs faster and accepts weights (Python 3.11+). Let me weight course grades, then add a home-price outlier:

from statistics import fmean, mean, median

grades = [85, 92, 78, 95]
weights = [0.20, 0.20, 0.30, 0.30]
print(fmean(grades))
print(fmean(grades, weights))

home_prices = [310_000, 295_000, 330_000, 305_000, 2_400_000]
print(mean(home_prices))
print(median(home_prices))

Output:

87.5
87.3
728000
310000
Python fmean with weights for grades and mean vs median on home prices with one outlier
Weights and outliers change the answer.

How does this work? The grades averaged 87.5; the 30% exams pulled it to 87.3. One $2.4 million home pushed the mean to 728000, while median() stayed at 310000.

Spread matters too: see standard deviation in Python.

Example 6: Use the .mean() Method in pandas and NumPy

Searching .mean python usually means an array or DataFrame. That’s a method, not statistics.mean():

import numpy as np
import pandas as pd

sales = np.array([1250, 980, 1500, 760])
print(np.mean(sales), sales.mean())

df = pd.DataFrame({"region": ["West", "East", "West", "East"],
                   "sales": [1250, 980, 1500, 760]})
print(df["sales"].mean())
print(df.groupby("region")["sales"].mean())

Output:

1122.5 1122.5
1122.5
region
East     870.0
West    1375.0
Name: sales, dtype: float64
NumPy np.mean and pandas Series.mean and groupby mean results for regional sales
The .mean() method in NumPy and pandas.

How does this work? Both NumPy calls gave 1122.5, the pandas column matched, and pandas groupby averaged each region.

pandas skips NaN by default; mean() doesn’t. For smoothing, see a mean filter in Python NumPy.

Common Mistakes with Python mean()

from statistics import mean

tests = [lambda: mean([]),
         lambda: mean(["42", "38"]),
         lambda: mean([42, None, 38]),
         lambda: mean(42, 38, 51)]
for n, test in enumerate(tests, 1):
    try:
        test()
    except Exception as err:
        print(f"{n}. {type(err).__name__}: {err}")

print("5.", mean([42, float("nan"), 38]))

Output:

1. StatisticsError: mean requires at least one data point
2. TypeError: can't convert type 'str' to numerator/denominator
3. TypeError: can't convert type 'NoneType' to numerator/denominator
4. TypeError: mean() takes 1 positional argument but 3 were given
5. nan
Common Python mean mistakes: empty list StatisticsError, strings, None, several arguments and NaN
Five mean() mistakes.
  1. Check for an empty list first.
  2. Convert strings with the Python map() function: map(float, data).
  3. Filter out None values.
  4. Pass one list, not separate numbers.
  5. One NaN turns the result into nan.

Wrapping Up the Python mean() Function

Python’s mean() averages any iterable and keeps exact types. Reach for fmean() for weights and median() when outliers skew things.

Next, browse more Python built-in functions and methods.

You might also like:

Quick Answers on Python mean() Function

How do I find the mean in Python?

Run from statistics import mean, then mean([4, 8, 9]).

Is there a built-in mean function in Python?

Not like sum(). It’s in the statistics module: import it, no install needed.

What does mean() return for a single value?

The value itself: mean([7]) returned 7.

Can mean() average booleans?

Yes. True counts as 1, so mean([True, False, True]) gave 0.6666666666666666.

Does statistics.mean() handle NaN or missing values?

No. NaN