0

This is probably the simplest question ever, please excuse me. I have the following line of code which doesn't act as expected.

s=3
t= [(1,2), (2,3), (3,3), (4,3), (5,4)]
[t.pop(i) for (i,l) in enumerate(t) if l[1]==s]
print(t)

and the result is

 [(1, 2), (3, 3), (5, 4)]

The second item should not be there (or should it?), what could be the reason? I also tried without list comprehension and ended up with the same result. Thanks in advance.

  • 1
    Removing elements from a list while iterating over it is problematic. One solution is to iterate over a copy of the list, so the deletions don't affect the iteration. Another solution is to produce a new list, containing the items you want to keep, rather than deleting anything. – jasonharper May 09 '22 at 03:33
  • 1
    Thank you, @DYZ and jasonharper I am able to fix the problem using your insights. – stochastic learner May 09 '22 at 04:03

0 Answers0