Best afterValues and names
Swapping two values
Swapping two variables looks trivial until you try the obvious thing and a value vanishes. Step through each version below and watch the state change, line by line. Toggle between the two cups and the raw variables — they are the same thing at two zoom levels.
Cup a holds juice and cup b holds milk. Swap them, so cup a ends with milk and cup b ends with juice.
a juiceb —noteCup a (the left cup) now holds juice.
Click a line, drag the slider, or use the ← → keys.
What you are looking at
Two cups: cup a holds juice, cup b holds milk. We want them swapped. The hard part is that pouring one cup into the other overwrites what was already there.
- Buggy — the swap a beginner writes first:
a = bthenb = a. Step it: the first line overwrites cupa's juice before it is ever saved, so both cups end up holding milk. The failure is shown by CPython, not asserted by us. - Procedural — save cup
ain a spare cup first (temp = a), then it is safe to overwrite. Watch the spare cup appear and rescue the juice. - Idiomatic — Python swaps both at once with
a, b = b, a: it packs the right-hand side into a pair and unpacks it back, so neither value is lost. One line, no spare.
Every state you see came from running the program under CPython's tracer at build time. The cups and the wording are human pedagogy laid on top — see how GlassBox stays honest.