Reductions
Sum and Mean
Sum a 6-element list in a single accumulator loop, then divide by the count to
get the mean. The replay shows total growing with each addition before mean
is computed in one final step.
By hand
With NumPy
a.sum() and a.mean() are reduction methods that collapse the entire array
to a scalar. The snapshot shows the input array's shape and dtype, then the
scalar results.
naive.py
values = [2, 5, 1, 8, 3, 5]
total = 0
for v in values:
total += v
mean = round(total / len(values), 2)
print('RESULT:', (total, mean))
library.py
import numpy as np
values = [2, 5, 1, 8, 3, 5]
a = np.array(values)
total = int(a.sum())
mean = round(float(a.mean()), 2)
print('shape:', a.shape)
print('dtype:', a.dtype)
print('sum:', total)
print('mean:', mean)
print('RESULT:', (total, mean))
shape: (6,)
dtype: int64
sum: 24
mean: 4.0
RESULT: (24, 4.0)
Implementation notes
- A reduction collapses an array along one or more axes to a smaller shape.
Both
sum()andmean()called without arguments reduce the entire array to a single scalar. a.sum()anda.mean()return NumPy scalars. Usingint()andfloat()converts them to plain Python types forRESULT, avoiding repr differences across NumPy versions (e.g.np.int64(24)vs24).- For the equivalent pure-Python idiom see
list-sum-meanin the python-data-basics book, andarithmetic-meanin the statistics chapter. - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.