Python loops and accumulators
Build a total one iteration at a time.
On this page
Variables, lists, and assignment.
- Build a total one iteration at a time.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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]) == 012
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
def total_of(values): total = 0 for value in values: total += value return total print(total_of([2, 4, 6]))assert total_of([]) == 0assert 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 |
Behind the scenes
How Python processes this code
Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.
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.