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.

(iter_accum2)

Note

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-1: Consider the following code:

    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    for w in nums:
       accum = 0
       accum = accum + w
    print(accum)
    

    What happens if you put the initialization of accum inside the for loop as the first instruction in the loop?

  • It will print out 10 instead of 55
  • The variable accum will be reset to 0 each time through the loop. Then it will add the current item. Only the last item will count.
  • It will cause a run-time error
  • Assignment statements are perfectly legal inside loops and will not cause an error.
  • It will print out 0 instead of 55
  • Good thought: the variable accum will be reset to 0 each time through the loop. But then it adds the current item.
        exceptions-2: 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