I know there are a lot of similar questions regarding this topic and I've researched enough to make me think this twist on the question hasn't been discussed or is just hard to find. I understand you can't just remove items from a list you are iterating unless you use some kind of copy or something. The example I come across time and
list=[1,2,3,4,5,6,7,8,9,10]
for x in list[:]:
if x==3:
list.remove(x)
list.remove(7)
This should remove 3, and 7 from the list. However, what if I have the following:
for x in list[:]:
if x==3:
list.remove(x)
list.remove(7)
if x==7:
list.remove(9)
This iteration removes 3,7, and 9. Since 7 "should" have been removed from a prior iteration, I don't actually want 9 to be removed (since there shouldn't be a 7 in the list anymore). Is there any way to do this?
You could add another check to the if statement: if x == 7 and x in list: list.remove(9)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With