Removing common values ​​from two lists in python

Hi, let's say that I have two lists in python and I want to remove the common values ​​from both lists. Potential solution:

x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [43, 3123, 543, 76, 879, 32, 14241, 342, 2, 3, 4]
for i in x:
    if i in y:
        x.remove(i)
        y.remove(i)

It seems correct, but it is not. The reason, in my opinion, is that by removing an item from the list, the index continues to iterate. Therefore, for two common values ​​in lists where the values ​​are next to each other, we will skip later values ​​(the code will not go through it). The result will be:

>>> x
[1, 3, 5, 6, 8, 9, 10]
>>> y
[43, 3123, 543, 76, 879, 32, 14241, 342, 3]

So, we lack value '3'.

Is the reason for this behavior the one I mentioned? or am I doing something else wrong?

+6
source share
5 answers

, x it x[:]. , . , 3

for i in x[:]:
      if i in y:
          x.remove(i)
          y.remove(i)

x,y = [i for i in x if i not in y],[j for j in y if j not in x]
+8

set.

a = list(set(y) - set(x))
b = list(set(x) - set(y))
+6
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

? .

+3

numpy, :

x, y = np.setdiff1d(x, y), np.setdiff1d(y, x)

numpy:

x, y = list(set(x).difference(y)), list(set(y).difference(x))
+2

, Python set - :

- :

>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> y = [43, 3123, 543, 76, 879, 32, 14241, 342, 2, 3, 4]
>>> sx = set(x)
>>> sy = set(y)
>>> sx.union(sy)
set([1, 2, 3, 4, 5, 6, 7, 8, 32, 43, 76, 342, 543, 879, 3123, 14241])

:

list(set(x).union(set(y)))
+1

Source: https://habr.com/ru/post/1017325/


All Articles