The Accumulator PatternΒΆ

One common programming “pattern” is to traverse a sequence, accumulating a value as we go, such as the sum-so-far or the maximum-so-far. That way, at the end of the traversal we have accumulated a single value, such as the sum total of all the items or the largest item.

The anatomy of the accumulation pattern includes:
  • initializing an “accumulator” variable to an initial value (such as 0 if accumulating a sum)
  • iterating (e.g., traversing the items in a sequence)
  • updating the accumulator variable on each iteration (i.e., when processing each item in the sequence)

For example, consider the following code, which computes the sum of the numbers in a list.

In the program above, notice that the variable accum starts out with a value of 0. Next, the iteration is performed 10 times. Inside the for loop, the update occurs. w has the value of current item (1 the first time, then 2, then 3, etc.). accum is reassigned a new value which is the old value plus the current value of w.

This pattern of iterating the updating of a variable is commonly referred to as the accumulator pattern. We refer to the variable as the accumulator. This pattern will come up over and over again. Remember that the key to making it work successfully is to be sure to initialize the variable before you start the iteration. Once inside the iteration, it is required that you update the accumulator.

Here is the same program in codelens. Step thru the function and watch the “running total” accumulate the result.



What would happen if we indented the print accum statement? Not sure? Make a prediction, then try it and find out.

Check your understanding

        exceptions-63: Rearrange the code statements so that the program will add up the first n odd numbers where n is provided by the user.n = int(input('How many even numbers would you like to add together?'))
thesum = 0
oddnumber = 1
for counter in range(n):
   thesum = thesum + oddnumber
   oddnumber = oddnumber + 2
print thesum
Next Section - The Accumulator Pattern with Lists