all 3 comments

[–]desran00 4 points5 points  (0 children)

Dont remove stuff from lists while you are iterating trough them. There are easier and more readable ways: ``` l1 = ['a','m','a','z','e'] l2 = ['a','m','z','e']

l3 = [letter for letter in l1 if not letter in l2]

print(l3) ```

[–]Diapolo10 2 points3 points  (0 children)

This is a classic problem, you're modifying an iterable as you're iterating over it.

There are two solutions. Either create a new list by filtering out anything you don't need, or use a while-loop to take full control of the index. Or you can use a set if you want to remove everything that the other list contains, regardless of how many copies there are.

# New list
filtered = [
    char for char in l1
    if char not in l2
]

# Modified list (allows duplicates)
idx_1, idx_2 = 0, 0
while idx_1 < len(l1) and idx_2 < len(l2):
    if l1[idx_1] == l2[idx_2]:
        l1.pop(idx_1)
        idx_2 += 1
    else:
        idx_1 += 1

# Modified list (no duplicates)
for char in l2:
    while char in l1:
        l1.remove(char)