Accumulate the total and count of a list of numbers in a single loop, then divide to get the mean. This is the building block for every aggregate function in later books.

By hand

The Pythonic way

statistics.mean handles the accumulation internally and raises StatisticsError on an empty list instead of a silent divide-by-zero. The float() call normalises the return type for integer inputs.

naive.py
values = [5, 10, 15, 20, 25, 30, 35, 40]
total = 0
count = 0
for v in values:
    total = total + v
    count = count + 1
mean = total / count
print('RESULT:', round(mean, 10))
library.py
import statistics
values = [5, 10, 15, 20, 25, 30, 35, 40]
mean = statistics.mean(values)
print('RESULT:', round(float(mean), 10))
RESULT: 22.5

Implementation notes

  • total and count stay as integers throughout the loop; the / operator produces a float at the final division step.
  • statistics.mean returns int when the mean divides evenly (e.g. mean([1, 2, 3])2) and float otherwise; wrapping with float() normalises the result to always be a float regardless of the data.