LearnFrenzy
Sign in Take a free test

Tricky Python Output Questions · Find the Error · Question 5

Bug: one negative number survives Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

All negative readings should be removed. Which statement correctly identifies the bug?

main.py
readings = [5, -1, -2, 7, -3]
for r in readings:
    if r < 0:
        readings.remove(r)
print(readings)
  • A remove() deletes the wrong value
  • B < 0 does not match -2
  • C Removing an item shifts the rest left while the loop index moves on, so -2 is skipped; build a new list: [r for r in readings if r >= 0] Correct
  • D Lists cannot hold negative numbers
Correct Answer: Option C

Never change the size of a list you are iterating over.

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