1

I'm not sure if I'm missing something, but I'm confused about this. I'm iterating over a list and removing some elements based on a condition. When the condition is met, it skips the next iteration. For example:

l = [1,1,2,3,1]
for i in l:
    print(f'checking {i} in {l}')
    if i == 1:
        print(f'removing')
        l.remove(i)

And this returns

checking 1 in [1, 1, 2, 3, 1]
removing
checking 2 in [1, 2, 3, 1]
checking 3 in [1, 2, 3, 1]
checking 1 in [1, 2, 3, 1]
removing

And then l=[2,3,1]. I think what is happening is that it's iterating by index, so when something is removed, the current index in the iteration is off by one. Is there a way to do this without skipping elements?

TheStrangeQuark
  • 2,257
  • 5
  • 31
  • 58

1 Answers1

1

Never mutate container you're iterating over, until you're really know what you're doing – iterate over l[:], remove from l.

Your understanding of problem is point on – for loop does not iterating over list values directly, changing the list size breaks indexing.

Slam
  • 8,112
  • 1
  • 36
  • 44