remove() and 'not in' function not working together
17:18 22 Dec 2025
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = [2, 4, 6]

for item in a:
    if item not in b:
        a.remove(item)

print(a)

This should return [2, 4, 6],

but instead returns [2, 4, 6, 8]

I thought it might be an indexing error under the hood, but:

a = [1, 2 3, 4, 5, 6, 7, 8, 10]
b = [2, 4, 6]

for item in a:
    if item not in b:
        a.remove(item)

print(a)

This ALSO returns [2, 4, 6, 8]

How?

python python-3.x list