15.6. List Accumulation¶
We have already encountered the accumulator pattern - where we loop through a list of values and combine them all. This is a natural thing to do with our lists. Say I want to total the points that were earned by a student on the quizzes. I might use the following program:
The key steps are described with comments. We always need to start with some initial value as our “accumulation variable”, loop through the items, and combine each value with the accumulation variable.
If I wanted to multiple a group of numbers together, my accumulator variable would need to
start with 1 (the multiplicative identity). At each step, I would multiply the current value
from the list by my accumulated value to get the new accumulated value. This is shown in
the animation below, using product
as the accumulator variable.
- 1
- That's the value the first time through the loop
- 2
- That's the value the second time through the loop
- 3
- That's the value the third time through the loop
- 4
- That's the value the fourth time through the loop
- 10
- That's the value the last time through the loop
What is the value of number at the end of the 3rd time through the loop?
If you want, you can indent the print
statement so that it prints the product
each time through the loop instead of just once at the end.
We can “accumulate” other types of data as well. Say I have a series of words stored in
a list. I can use the accumulator pattern to build up one string with all of the words.
My accumulator variable will need to start with an appropriate empty value for a string,
which is ""
.
The following program should calculate the average of some numbers by adding them all up before dividing by the number of values there are and printing out the answer. Put the blocks in the correct order and indentation. You will not need them all.