Adding up a list
Adding up a list is the most common loop you will ever write: keep a running total, and add each number onto it. The trap is one character — = where you meant += — and the state pane shows exactly what it costs. Try Predict mode and call each total before you reveal it.
Add up all the numbers in the list and report the total.
Adding up a list — the overwrite bug execution-derived · CPython
variables
state after line 1 runs
| variable | value |
|---|---|
nums | [3,8,5,2] |
step 1 / 11
Click a line, drag the slider, or use the ← → keys.
What you are looking at
There is no cup or pile here — just one number, total, that you watch grow (or fail to). Keep your eye on it as each n comes through the loop.
- Buggy —
total = nreplaces the total every pass, so the 3 is gone the moment 8 arrives. total ends at 2 — just the last number, never the sum. The failure is shown by CPython, not asserted by us. - Procedural —
total = total + nadds onto what is already there. Watch total climb 0 → 3 → 11 → 16 → 18. That is the accumulator pattern, and it underlies counting, averaging, and almost every loop that summarises a list. - Compact —
total = sum(nums)does the whole job in one built-in call (18). You can't step inside it — it is C code — so there is nothing to watch line by line. That is the trade-off the Compact register names: concise, but the work happens off-screen.
Every state you see came from running the program under CPython's tracer at build time — see how GlassBox stays honest.