Skip to content
Discussion options

You must be logged in to vote

a) Predicted output

[4, 8]

No, the list is not empty. Half the values survive.

b) Trace by hand

A for loop over a list uses a hidden index that goes up by 1 each pass. When you remove an item, the remaining items shift left, but the index still moves forward.

Pass Index List at start n Action List after
1 0 [2, 4, 6, 8] 2 remove 2 [4, 6, 8]
2 1 [4, 6, 8] 6 remove 6 [4, 8]
3 2 [4, 8] none index 2 is past the end, loop stops [4, 8]

The loop never looks at 4 or 8.

  • After 2 is removed, 4 slides into index 0, but the loop has already moved on to index 1, so it skips 4 and lands on 6.
  • After 6 is removed, 8 slides into index 1, but the loop moves to index 2, which no longer exists…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Temple-Daemon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants