Step-by-Step Execution
Initial list
arr = [1, 2, 3]✅ 1st Iteration
List becomes:
[2, 3]Now Python moves to the next index (index 1).
✅ 2nd Iteration
Now the list is:
[2, 3]Index 1 has:
i = 3So:
arr.remove(3)List becomes:
[2]✅ Loop Ends
There is no next element to continue.
✅ Final Output
[2]Why This Happens (Important Concept)
-
You are modifying the list while looping over it
-
When an element is removed:
-
The list shifts to the left
-
The loop skips elements
-
-
This causes unexpected results
✅ Correct Way to Remove All Elements
✔️ Option 1: Loop on a copy
✔️ Option 2: Use clear()
arr.clear()Key Interview Point
❌ Never modify a list while iterating over it directly.


0 Comments:
Post a Comment