Removing common values from two lists in python
Just slight change your code,Iterate through the copy of x
it's x[:]
.You are modifying the list while iterating over it. So that's why you are missing value 3
for i in x[:]:
if i in y:
x.remove(i)
y.remove(i)
And alternative method
x,y = [i for i in x if i not in y],[j for j in y if j not in x]
You can also use difference of set
objects.
a = list(set(y) - set(x))
b = list(set(x) - set(y))
z=[i for i in x if i not in y]
w=[i for i in y if i not in x]
x=z
y=w
That should do the trick? It's a bit less memory efficient.