Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twist? on removing items from a list while iterating in python

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?

like image 210
thatandrey Avatar asked Jun 12 '26 07:06

thatandrey


1 Answers

You could add another check to the if statement: if x == 7 and x in list: list.remove(9)

like image 160
Lukeclh Avatar answered Jun 13 '26 21:06

Lukeclh