Python
Arithmetic Mean
Average Calculation
Duplicate Question
Programming Tutorial

Calculating arithmetic mean one type of average in Python

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

The arithmetic mean (average) of a collection of numbers is the sum divided by the count. In Python, the most straightforward way is sum(data) / len(data), but the standard library provides statistics.mean() for correctness with edge cases, and NumPy provides numpy.mean() for high-performance computation on large arrays. Each approach has different tradeoffs in precision, performance, and handling of empty inputs. This article covers all common methods with their appropriate use cases.

Using sum() and len()

python
1numbers = [10, 20, 30, 40, 50]
2
3mean = sum(numbers) / len(numbers)
4print(mean)  # 30.0
5
6# Works with floats
7prices = [9.99, 14.50, 3.75, 22.00]
8avg_price = sum(prices) / len(prices)
9print(avg_price)  # 12.56
10
11# Works with negative numbers
12temps = [-5, 3, 7, -2, 15, 8]
13avg_temp = sum(temps) / len(temps)
14print(f"{avg_temp:.1f}")  # 4.3

This approach raises ZeroDivisionError on empty lists:

python
1empty = []
2# mean = sum(empty) / len(empty)  # ZeroDivisionError
3
4# Safe version
5mean = sum(empty) / len(empty) if empty else 0

Using statistics.mean()

The statistics module (Python 3.4+) handles Fraction and Decimal types correctly:

python
1from statistics import mean
2
3numbers = [10, 20, 30, 40, 50]
4print(mean(numbers))  # 30
5
6# Works with any iterable of numbers
7print(mean((1, 2, 3)))              # 2
8print(mean(range(1, 11)))           # 5.5
9
10# Handles Fraction and Decimal precisely
11from fractions import Fraction
12fracs = [Fraction(1, 3), Fraction(2, 3), Fraction(1, 6)]
13print(mean(fracs))  # 7/18 (exact, no floating-point error)
14
15from decimal import Decimal
16prices = [Decimal("9.99"), Decimal("14.50"), Decimal("3.75")]
17print(mean(prices))  # 9.413333333333333333333333333 (Decimal precision)

statistics.mean() raises StatisticsError on empty input:

python
1from statistics import mean, StatisticsError
2
3try:
4    mean([])
5except StatisticsError as e:
6    print(e)  # mean requires at least one data point

Using numpy.mean()

NumPy is the best choice for large datasets and multi-dimensional arrays:

python
1import numpy as np
2
3# Basic usage
4data = [10, 20, 30, 40, 50]
5print(np.mean(data))  # 30.0
6
7# NumPy arrays
8arr = np.array([1.5, 2.5, 3.5, 4.5])
9print(arr.mean())  # 3.0
10
11# Large dataset (much faster than pure Python)
12big_data = np.random.randn(1_000_000)
13print(np.mean(big_data))  # ~0.0 (standard normal)
14
15# Multi-dimensional arrays
16matrix = np.array([[1, 2, 3],
17                   [4, 5, 6],
18                   [7, 8, 9]])
19
20print(np.mean(matrix))          # 5.0 (all elements)
21print(np.mean(matrix, axis=0))  # [4. 5. 6.] (column means)
22print(np.mean(matrix, axis=1))  # [2. 5. 8.] (row means)

Weighted Mean

python
1import numpy as np
2
3scores = [85, 90, 78, 92]
4weights = [0.2, 0.3, 0.2, 0.3]
5
6weighted_avg = np.average(scores, weights=weights)
7print(weighted_avg)  # 87.1
8
9# Manual calculation for verification
10manual = sum(s * w for s, w in zip(scores, weights)) / sum(weights)
11print(manual)  # 87.1

Using functools.reduce()

A functional programming approach:

python
1from functools import reduce
2
3numbers = [10, 20, 30, 40, 50]
4
5total = reduce(lambda acc, x: acc + x, numbers)
6mean = total / len(numbers)
7print(mean)  # 30.0
8
9# Or in a single expression
10mean = reduce(lambda acc, x: acc + x, numbers) / len(numbers)

This is less readable than sum() / len() and generally not preferred for this task.

Running (Cumulative) Mean

python
1# Running mean — average up to each index
2numbers = [10, 20, 30, 40, 50]
3
4running_means = []
5for i in range(len(numbers)):
6    running_means.append(sum(numbers[:i+1]) / (i + 1))
7
8print(running_means)  # [10.0, 15.0, 20.0, 25.0, 30.0]
9
10# NumPy approach
11import numpy as np
12arr = np.array(numbers)
13running = np.cumsum(arr) / np.arange(1, len(arr) + 1)
14print(running)  # [10. 15. 20. 25. 30.]

Other Types of Averages

python
1from statistics import mean, median, mode, harmonic_mean, geometric_mean
2
3data = [2, 4, 4, 4, 5, 5, 7, 9]
4
5print(f"Arithmetic mean: {mean(data)}")       # 5.0
6print(f"Median: {median(data)}")              # 4.5
7print(f"Mode: {mode(data)}")                  # 4
8print(f"Harmonic mean: {harmonic_mean(data):.2f}")   # 3.76
9print(f"Geometric mean: {geometric_mean(data):.2f}") # 4.30 (Python 3.8+)
Average TypeFormulaUse Case
Arithmetic meanSum / CountGeneral-purpose average
MedianMiddle valueRobust to outliers
ModeMost frequentCategorical data
Harmonic meann / (sum of 1/x)Rates, speeds, ratios
Geometric meannth root of productGrowth rates, percentages

Performance Comparison

python
1import timeit
2import numpy as np
3from statistics import mean as stats_mean
4
5data_list = list(range(100_000))
6data_array = np.array(data_list)
7
8# Pure Python: sum/len
9t1 = timeit.timeit(lambda: sum(data_list) / len(data_list), number=100)
10
11# statistics.mean
12t2 = timeit.timeit(lambda: stats_mean(data_list), number=100)
13
14# numpy.mean on list (includes conversion)
15t3 = timeit.timeit(lambda: np.mean(data_list), number=100)
16
17# numpy.mean on array (fastest)
18t4 = timeit.timeit(lambda: np.mean(data_array), number=100)
19
20# Typical results:
21# sum/len:         ~0.05s
22# statistics.mean: ~0.50s (slower due to type handling)
23# np.mean(list):   ~0.15s (list-to-array conversion overhead)
24# np.mean(array):  ~0.001s (fastest)

Common Pitfalls

  • Using sum()/len() on empty lists: This raises ZeroDivisionError. Always check if data: first, or use statistics.mean() which raises a descriptive StatisticsError instead.
  • Integer division in Python 2: In Python 2, sum([1,2,3]) / len([1,2,3]) returns 2 (integer division). Use from __future__ import division or cast to float. Python 3 always returns a float for /.
  • Floating-point precision with sum()/len(): Summing many floats accumulates rounding errors. statistics.mean() uses a more accurate algorithm internally. For financial calculations, use Decimal types with statistics.mean().
  • Calling np.mean() on a Python list repeatedly: Each call converts the list to a NumPy array first, adding overhead. Convert to a NumPy array once and reuse it if you need multiple operations.
  • Confusing np.mean() with np.average(): np.mean() computes an unweighted average. np.average() supports an optional weights parameter for weighted means. They return different results when weights are provided.

Summary

  • Use sum(data) / len(data) for simple, quick calculations on lists
  • Use statistics.mean() for type-safe computation with Fraction, Decimal, or when descriptive error handling is needed
  • Use numpy.mean() for large datasets and multi-dimensional arrays (fastest on NumPy arrays)
  • Use numpy.average(data, weights=w) for weighted means
  • Always handle empty inputs — sum()/len() raises ZeroDivisionError, statistics.mean() raises StatisticsError

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms