Question 10
Back to Exercise
What is the output of the following Python program?
nums = [1, 2, 2, 3, 4]
for n in nums:
if n == 2:
nums.remove(n)
print(nums)
- A [1, 2, 3, 4] Correct
- B [1, 3, 4]
- C [1, 2, 2, 3, 4]
- D RuntimeError
Correct Answer: Option A
Removing the first 2 (index 1) shifts the second 2 into index 1; the loop moves on to index 2, which is now 3, so the second 2 is never checked.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!