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]) == 0Output
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
1
def total_of(values):2
total = 03
for value in values:4
total += value5
return total6
7
print(total_of([2, 4, 6]))8
assert total_of([]) == 09
assert total_of([-2, 2]) == 0Follow 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
| Step / line | What happens | State after step | Output 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.