Linear search
To find something in an unsorted list, you check each element in turn until you spot it. The subtle part is what you report: a search returns where the value is — its index — not the value itself, which you already knew. Step through and watch found.
Find WHERE a target value sits in the list, and report its index (or -1 if it is not there).
Linear search — value where the index belongs execution-derived · CPython
state after line 1 runs
nums 48151623
step 1 / 15
Click a line, drag the slider, or use the ← → keys.
What you are looking at
The list is [4, 8, 15, 16, 23] and we are looking for 15. The right answer is its index, 2. found starts at -1, a sentinel that means "not found yet" — no real index is negative, so it can never be mistaken for an answer.
- Buggy —
found = nums[i]stores the value that matched, so it ends at15: the thing we searched for, not where it lives. Useless as a position. - Procedural —
found = irecords the index, so it ends at2. One character apart, and only the state pane makes the difference undeniable. - Compact —
found = nums.index(target)scans and returns the position (2) in one call. Concise, but it raises an error if the target is absent — guard it withtarget in numswhen that can happen.
Every state you see came from running the program under CPython's tracer at build time — see how GlassBox stays honest.