Question 5
Back to Exercise
All negative readings should be removed. Which statement correctly identifies the bug?
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!