Python loops and accumulators

Build a total one iteration at a time.

Python
def total_of(values):
    total = 0
    for value in values:
        total += value
    return total

print(total_of([2, 4, 6]))
assert total_of([]) == 0
assert total_of([-2, 2]) == 0
Output
12

Explanation

A for loop visits each item from an iterable. An accumulator keeps the partial result between iterations.

Initialize total once before the loop. Moving that initialization inside the loop would discard the previous partial sum. An empty list leaves the total at zero.

Explore the dry run
Guided walkthroughReady
1def total_of(values):
2 total = 0
3 for value in values:
4 total += value
5 return total
6
7print(total_of([2, 4, 6]))
8assert total_of([]) == 0
9assert total_of([-2, 2]) == 0

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Call total_of with three values.values = [2, 4, 6]
—
Start the accumulator.total = 0
—
First iteration adds 2.value = 2, total = 2
—
Second iteration adds 4.value = 4, total = 6
—
Third iteration adds 6.value = 6, total = 12
—
Iteration ends and the function returns 12.return = 12
—
Print the returned total.return = 12
12
The two assertions check empty input and cancellation.return = 12
12

Cost and common mistakes

O(n) time and O(1) auxiliary space for n fixed-size numbers.

  • Do not reset the accumulator inside the loop.
  • Inputs must support addition with the chosen starting value.

Try it yourself

Adapt the function to count only positive values in [-2, 0, 3, 5].

Reveal answer and reasoning

Start count at 0 and increment only when value > 0. The answer is 2.

Further reading