Python Tutorial: Calculate Average of Numbers in a List
Calculating an average is easy when the input is a short, nonempty list of ordinary numbers. Real programs need to handle missing values, weighting, large datasets and the distinction between arithmetic mean and other statistics. Python offers several standard-library approaches, and each has useful trade-offs.
Use sum(values) / len(values) for a simple educational example, statistics.mean() for clear statistical intent, and statistics.fmean() when floating-point speed is appropriate. Neither a short expression nor a library call removes the need to validate data.
The arithmetic mean is the sum of the observations divided by their count. Handle an empty sequence explicitly before dividing, and avoid silently treating missing entries as zero.
numbers = [10, 20, 30, 40]
if not numbers:
raise ValueError("No observations")
print(sum(numbers) / len(numbers)) # 25.0
The statistics module communicates the operation more directly. mean() raises StatisticsError on empty input; fmean() returns a floating-point result and is suitable for many numerical workflows. Neither function should be used without validating relevant inputs.
from statistics import mean, fmean
values = [1, 2, 3, 4]
print(mean(values))
print(fmean(values))
When some observations contribute more than others, calculate sum(value times weight) divided by total weight. Validate lengths and the business meaning of negative or zero weights. For many tasks, frequency weights should be nonnegative.
values = [80, 90, 70]
weights = [2, 3, 1]
if len(values) != len(weights) or sum(weights) <= 0:
raise ValueError("Invalid weights")
weighted = sum(v*w for v, w in zip(values, weights)) / sum(weights)
print(weighted)
Binary floating-point can represent many decimals only approximately. When monetary calculations require fixed decimal precision, use Decimal values constructed from strings and a defined rounding policy.
from decimal import Decimal
costs = [Decimal("1.10"), Decimal("2.20")]
print(sum(costs) / len(costs)) # 1.65
Decide whether an absent observation should be rejected, excluded or recorded separately. NaN can propagate into a mean, and replacing bad inputs with zero alters the meaning of the data. Document the cleaning rule so results can be reproduced.
records = [8, None, 12]
valid = [x for x in records if x is not None]
if not valid:
raise ValueError("No valid numbers")
print(sum(valid) / len(valid))
A stream can be averaged without storing every value. Track a running count and total, or use an incremental update rule when an enormous sum is undesirable. For production analytics, compare stability and precision against tested library implementations.
count = 0
average = 0.0
for value in (5, 9, 7):
count += 1
average += (value - average) / count
print(average)
NumPy supports efficient numeric arrays and means along an axis. A mean of a matrix can represent one number per column or row, so specify the intended axis. For NaN-bearing data, use a deliberate missing-data policy such as nanmean when appropriate.
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
print(np.mean(matrix, axis=0)) # [2. 3.]
An average can be skewed by outliers. Median describes a middle ordered value and mode identifies frequently occurring values. Choose the statistic that answers the real question and show the sample count and distribution context.
from statistics import mean, median
values = [2, 3, 4, 100]
print(mean(values)) # 27.25
print(median(values)) # 3.5
Python makes arithmetic means convenient, but reliable results depend on validated input, a defined denominator, appropriate weighting and precision, and a clear choice of statistic. Test the empty, missing-value and outlier cases before a result informs a real decision.
