Section 27.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 multiply 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.
Checkpoint 27.6.1.
What is the value of product
at the end of the 3rd time through the loop?
1
That’s the value the first time through the loop
2
That’s the value the second time through the loop
6
Correct. That’s the value the third time through the loop.
24
That’s the value the fourth time through the loop
120
That’s the value the last time through the loop
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 ""
.
Checkpoint 27.6.2.
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.
numbers = [90, 80, 75, 90, 83]
sum = 0
---
for number in numbers:
---
sum = sum + number
---
sum = sum + numbers #paired
---
average = sum / len(numbers)
print(average)
You have attempted
of
activities on this page.