← Python lessons

The Accumulator Pattern

An accumulator stores a result built up as a loop runs. Initialize it before the loop, update it when needed inside the loop, and use the completed result after the loop. A total changes by addition, a collection gains items, and a best-so-far value changes only when a better candidate appears.

Summing

Start a total at 0, then add each item to it:

total = 0
for roll in [3, 5, 2]:
    total = total + roll
print(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.

Collecting results in a list

Create the result list before the loop. Append one result on each repetition:

updated = []
for score in [3, 7, 4]:
    updated.append(score + 1)
print(updated)

The result grows from [] to [4], then [4, 8], then [4, 8, 5]. Creating the list inside the loop would discard earlier entries. In a function that builds a complete list, return it after the loop finishes.

Counting

To count how many items match a condition, start at 0 and add 1 each time the condition holds:

big_rolls = 0
for roll in [3, 5, 2, 6]:
    if roll >= 4:
        big_rolls = big_rolls + 1
print(big_rolls)

Here the counter records how many rolls are at least 4. A count adds 1 for each match; a sum adds the matching value itself.

Your turn: count matches

Count how many values are at least 4. Print the count, not the sum of those values.

rolls = [2, 6, 4, 1]
count = 0
# Count the matching values, then print count.

Expected output

2

The shortcut for a plain sum

If you only need to add numbers up, sum() does it in one line:

rolls = [3, 5, 2]
print(sum(rolls))

Use sum() when adding existing numbers is the whole task. In these exercises, use an explicit loop when practising how a result is updated step by step, especially when collecting values into a list.

See also: For loops, The range() function.

Optional practice: sum matching values

Add a loop that adds up only the rolls of 4 or more, then print the total. The accumulator is already started for you.

rolls = [3, 5, 2, 6, 4]
total = 0
# add a loop with an if that adds the roll to total, then print total (four lines)

Expected output

15

Practise this in the free Python course, where every exercise checks your code instantly.