The Accumulator Pattern
An accumulator is a variable that builds up a result as a loop runs. Set it before the loop, update it inside the loop, and use it after the loop.
Summing
Start a total at 0, then add each item to it:
total = 0for roll in [3, 5, 2]: total = total + rollprint(total)total starts at 0, becomes 3, then 8, then 10. The starting value
has to be set before the loop — otherwise there is nothing to add the first
item to.
Counting
To count how many items match a condition, start at 0 and add 1 each time
the condition holds:
big_rolls = 0for roll in [3, 5, 2, 6]: if roll >= 4: big_rolls = big_rolls + 1print(big_rolls)This prints 2: two rolls are 4 or more. A count adds 1 for each match. A sum adds the value itself.
Collecting results in a list
Create an empty list before the loop. Append one result each time around:
updated = []for score in [3, 7, 4]: updated.append(score + 1)print(updated)The list grows from [] to [4], then [4, 8], then [4, 8, 5]. Creating the list inside the loop would throw away earlier items. In a function, return the list after the loop finishes.
See also: For loops, The range() function.
Your turn
Count how many values are 4 or more. Print the count, not the sum of those values.
2
rolls = [2, 6, 4, 1]count = 0# add a loop with an if that adds 1 to count, then print countAdvanced reading
- Augmented assignment — write
total += rollinstead oftotal = total + roll. - Choosing the starting value — products start at
1, text at"", tallies at{}. - Built-in accumulators —
sum(),len(),max()andmin()do common loops in one call.