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


3 answers


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



+1


source


Remember you are deleting the original list and repeating the copy. The copy still has 7, so 9 will be deleted as well.



0


source


Try it.

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for x in list1:
    if x == 3:
        list1.remove(x)
        list1.remove(7)
    if x == 7:
        list1.remove(9)
print list1

Output: [1, 2, 4, 5, 6, 8, 9, 10]

      

Instead of repeating a new list, you can work with the same.

0


source







All Articles