Why does a loop that removes items from the list it is walking silently skip elements, with no error at all?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
Here is the buggy pattern again, this time on a list of five 4s:
L = [4, 4, 4, 4, 4] e = 4 for elem in L: if elem == e: L.remove(e)
Work out by hand what L holds once this loop finishes — track the position counter yourself, pass by pass — and assign that list, written out as a list literal, to final_list.
The loop pointer against the left shift
Trace for elem in L: if elem == e: L.remove(e) on L = [1, 2, 2, 2] removing 2s, writing the pointer position and list contents each pass down to [1, 2].
A silent failure with no error raised
State that Python raises nothing and the code reads as correct, with the surviving wrong elements as the only evidence of the fault.
The remove_duplicates trap on two lists
Trace for e in L1: if e in L2: L1.remove(e) with L1 = [10, 20, 30, 40] and L2 = [10, 20, 50, 60], ending at the wrong [20, 30, 40].
Appending or inserting during iteration
Record that appending to the list being walked never terminates, and that inserting at or before the pointer makes one element come up a second time.