LearnFrenzy
Sign in Take a free test

Loops · Predict the Output · Question 10

Removing items while iterating a list Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

What is the output of the following Python program?

main.py
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links