Computer Science I / Loops and Repeated Computation
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
  1. Delete element 0. Where does the old element 1 go? Where does the loop index go next?
  2. 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'.

Read the lesson: Loops and Repeated Computation →

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