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.
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()
This approach raises ZeroDivisionError on empty lists:
Using statistics.mean()
The statistics module (Python 3.4+) handles Fraction and Decimal types correctly:
statistics.mean() raises StatisticsError on empty input:
Using numpy.mean()
NumPy is the best choice for large datasets and multi-dimensional arrays:
Weighted Mean
Using functools.reduce()
A functional programming approach:
This is less readable than sum() / len() and generally not preferred for this task.
Running (Cumulative) Mean
Other Types of Averages
| Average Type | Formula | Use Case |
| Arithmetic mean | Sum / Count | General-purpose average |
| Median | Middle value | Robust to outliers |
| Mode | Most frequent | Categorical data |
| Harmonic mean | n / (sum of 1/x) | Rates, speeds, ratios |
| Geometric mean | nth root of product | Growth rates, percentages |
Performance Comparison
Common Pitfalls
- Using
sum()/len()on empty lists: This raisesZeroDivisionError. Always checkif data:first, or usestatistics.mean()which raises a descriptiveStatisticsErrorinstead. - Integer division in Python 2: In Python 2,
sum([1,2,3]) / len([1,2,3])returns2(integer division). Usefrom __future__ import divisionor 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, useDecimaltypes withstatistics.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()withnp.average():np.mean()computes an unweighted average.np.average()supports an optionalweightsparameter 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 withFraction,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()raisesZeroDivisionError,statistics.mean()raisesStatisticsError
Related reading
- Calculating Pearson correlation and significance in Python
- Calculating Precision, Recall and F-score in one pass - python
- Calculating the similarity of two lists
- Call a async function/property inside __str__
- Call a python function from jinja2
- Call int function on every list element?
- Call predict function for nearest neighbor knn classifier with Python scikit sklearn
- Calling a base class's classmethod in Python
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseData 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.