Minimum, Total and Average
A report often needs several facts from the same list. You can update more than one accumulator during one loop.
Track a minimum and a total
For a non-empty list, start the minimum with the first real value. Starting
at 0 would be wrong when every measurement is positive: none could be
smaller than zero.
distances = [12, 7, 10]shortest = distances[0]total = 0for distance in distances: if distance < shortest: shortest = distance total = total + distanceprint(shortest)print(total)The minimum changes only when a smaller value appears. The total changes on every turn.
Calculate a mean
The arithmetic mean is the total divided by the number of measurements. In the preceding example, the total is 29 and there are 3 measurements.
distances = [12, 7, 10]total = 0for distance in distances: total = total + distancemean = total / len(distances)print(mean)print(round(mean))Division gives approximately 9.6667; round(mean) gives the integer 10. With one argument, round() rounds to a whole number. Exact halfway cases choose the even integer: round(10.5) is 10, and round(11.5) is 12.
Calculate the mean after the loop, once the total includes every measurement. An empty list would give a divisor of zero, so this lesson's examples require a non-empty list.
Trace the two values
For the measurements [18, 12, 20], start lowest at 18 and total at zero. Write both values after each measurement is processed. Explain why the final measurement changes the total but not the lowest value.
Check your trace: the pairs are (18, 18), (12, 30) and (12, 50), written as (lowest, total).
See also: The Accumulator Pattern.
Your turn
Calculate the mean from total and the number of measurements, then print it.
14.0
measurements = [8, 12, 16, 20]total = sum(measurements)# add two lines: calculate mean, then print it