Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing common values from two lists in python

Hi let's say that I have two lists in python and I want to remove common values from both lists. A potential solution is:

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, I guess, is because by removing an item from the list the index continues to iterate. Therefore, for two common values in the lists where the values are near each other we will be missing the later values (the code will not iterate through it). The result would be:

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

So we are missing the value '3'.

Is the reason of that behaviour the one that I mentioned? or am I doing something else wrong?

like image 453
MaPy Avatar asked May 17 '17 20:05

MaPy


People also ask

How do you find the common values in two lists in Python?

Method 2:Using Set's intersection property Convert the list to set by conversion. Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets.

How do you find common items between two lists?

Using sets Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets.


2 Answers

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]
like image 138
Rahul K P Avatar answered Nov 14 '22 09:11

Rahul K P


You can also use difference of set objects.

a = list(set(y) - set(x))
b = list(set(x) - set(y))
like image 38
Taku Avatar answered Nov 14 '22 09:11

Taku