Twist? when removing items from a list while iterating in python
I know there are many similar questions on this topic, and I have researched enough to make me think that this twist in the question has not been discussed or is simply difficult to find. I understand that you cannot just remove items from the list you are executing unless you are using some kind of copy or something. Example: I am in 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, 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" be removed from the previous iteration, I actually don't want to remove 9 (since there should no longer be 7 in the list). Is there any way to do this?
+3
source to share