thatandrey
thatandrey

Reputation: 287

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?

Upvotes: 3

Views: 132

Answers (3)

Sesha
Sesha

Reputation: 202

Try this.

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 iterating over a new list, you can work on the same one.

Upvotes: 0

Lukeclh
Lukeclh

Reputation: 231

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

Upvotes: 1

Code-Apprentice
Code-Apprentice

Reputation: 83577

Remember that you are removing from the original list and iterating over a copy. The copy still has the 7 in it, so the 9 will be removed as well.

Upvotes: 0

Related Questions