Step-by-step execution:
Initial array:
arr = [1, 2, 3]
The for loop iterates over the list, but note — the list is changing during iteration.
Iteration 1:
-
i = 1
arr.remove(1) → removes the first occurrence of 1
-
Now arr = [2, 3]
But — Python’s for loop moves to the next index (index 1)
๐ So now it skips checking the element at index 0 (which became 2 after removal).
Iteration 2:
-
Next element (at index 1) is 3
arr.remove(3) removes 3
-
Now arr = [2]
Loop ends (because Python has already iterated through what it thinks were 3 elements).
✅ Final Output:
[2]๐น Why does this happen?
Because modifying a list while looping over it confuses the iterator —
the loop skips elements since the list shrinks and indexes shift.
๐ก Best Practice:
Never modify a list while iterating over it.
Instead, use a copy:
So the correct answer is ✅ [2]


0 Comments:
Post a Comment