-2

I have a for loop as such:

for i in list1:
    if i in list2:
        list1.remove(i)

It iterates over a list of strings "list1", checks if that string is in the other list "list2" and if it is, removes it from "list1".

However, after removing a string, instead of i then becoming the next string, it becomes the string after that. In other words, if I have a list ['a', 'b', 'c', 'd', 'e'] and I iterate over it, if the iterator "i" = 'b' and I need to remove 'b', after removing it then on the next loop iteration "i" = 'd' instead of "i" = 'c'.

My question is, how to fix this while still using for loop? Can I still use a for loop or do I have to use a while loop and iterate backwards 1 every time I remove a string?

1 Answers1

1

It's best not to modify a list while iterating over it. You can instead use a list comprehension to filter.

list1 = [x for x in list1 if x not in list2]
Unmitigated
  • 76,500
  • 11
  • 62
  • 80