Solved

My loop only processes every second item

OllieGrantOP

I'm removing invalid readings from a list inside a for loop, but some invalid ones stay.

for r in readings:
    if r < 0:
        readings.remove(r)
2

Comments 5

Log in to join the discussion.

Log in Create account
  1. EmmaCodes Solutionreplies: 1

    Never change a list while looping over it. When you remove an item, everything shifts left and the loop skips the next one.

    Build a new list instead:

    readings = [r for r in readings if r >= 0]
    7
    1. OllieGrantOP

      Ahh, so two negatives in a row → the second one survives. That matches what I saw.

      0
    2. BellaRossireplies: 1

      If you really need to modify in place, loop over a copy: for r in readings[:]:. But the list comprehension is cleaner.

      5
      1. AmeliaRuns

        The "Changed the caller's list" challenge has a related trap with functions.

        6
      2. NoahLoops

        This one deserves to be in a "top 10 beginner bugs" list.

        4