Step-by-Step Execution
-
Initial list:
nums = [1, 2, 3, 4] -
Iteration 1:
-
i = 1
-
Remove 1 → list becomes [2, 3, 4]
-
The iterator moves to next index (1) → which now points to 3.
-
-
Iteration 2:
-
i = 3
-
Remove 3 → list becomes [2, 4]
-
The iterator moves to next index (2), but list length is now 2 → loop stops.
-
-
Loop ends.
Final Output:
[2, 4]Key Takeaway:
Never modify (add/remove) a list while iterating directly over it —
it causes skipped elements or unexpected results.
✅ Better Way (Safe Approach):
.png)

0 Comments:
Post a Comment