Best afterLinear search
Filtering a list
Filtering — keeping only the items that pass some test — is the everyday move behind "find the data that matters." The safe way is to build a new list. The tempting way is to delete the unwanted items in place, and the state pane shows exactly why that backfires.
Keep only the numbers greater than 10, and leave the original list untouched.
Filtering a list — deleting as you go execution-derived · CPython
state after line 1 runs
nums 432218715
step 1 / 12
Click a line, drag the slider, or use the ← → keys.
What you are looking at
The list is [4, 3, 22, 18, 7, 15] and we want only the numbers over 10. The right answer is [22, 18, 15].
- Buggy — deletes each small number from
numswhile looping over it. Removing4shifts3into a slot the loop has already passed, so3is skipped and survives.numsends as[3, 22, 18, 15]— a small number leaked through, and the original list is destroyed. - Procedural — copies the passing numbers into a fresh list
bigand never touchesnums. Nothing shifts under the loop, so nothing is skipped. - Compact —
[n for n in nums if n > 10]builds the new list in one expression. Python still runs it as a loop — watchntake each value — andbigappears complete at the end.
Every state you see came from running the program under CPython's tracer at build time — see how GlassBox stays honest.