Practice question · Multiple choice
Modifying a list while looping over it can silently skip elements. Why does removing an item mid-iteration cause that?
Hints
- Delete element 0. Where does the old element 1 go? Where does the loop index go next?
- Trace [a,b,c,d] removing every item. Which ones does the loop actually visit?
Show the answer
B. Because the index advances while the list shifts left beneath it
Why
The list shifts left and the index moves right, so each removal skips the element that slid into place, remove every item from [a,b,c,d] and you visit a and c. The fixes are to iterate over a copy or build a new list, and it is the standard reason 'why did my filter miss half the entries'.
Practise Loops and Repeated Computation
The app has 6 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on Loops and Repeated Computation
- Order the parts of a correct while loop so that it counts up and then stops.
- Match each loop keyword or form to what it does.
- The counter starts at i = 0. Select every loop below that runs its body exactly 5 times.
- An off-by-one error in a loop boundary usually causes a crash, which is what makes it easy to find.