-3
>>> x1=[["x1","y1"],["x1","x2"]]  
>>> x2=[["x1","y1"],["x1","x2"],["x2","y2"]]  
>>> x2-x1  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
>>> set(x2)-set(x1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

I want to get the difference between two lists, the result I want here is ["x2","y2"]. How can I get it?

gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79
showkey
  • 482
  • 42
  • 140
  • 295

2 Answers2

3

You can do it as follows by checking element-wise:

x1=[["x1","y1"],["x1","x2"]]  

x2=[["x1","y1"],["x1","x2"],["x2","y2"]]

>>> print [i for i in x2 if i not in x1]
[['x2', 'y2']]
sshashank124
  • 31,495
  • 9
  • 67
  • 76
2

The other solution runs in O(N^2), where as this solution runs in O(N + M) time complexity.

x1 = [["x1", "y1"], ["x1", "x2"]]
x2 = [["x1", "y1"], ["x1", "x2"], ["x2", "y2"]]
set1 = {tuple(item) for item in x1}
print [item for item in x2 if tuple(item) not in set1]
# [['x2', 'y2']]

Just convert the first set of items to a list of tuples and then create a set with the tuples. Then, for every item in the next list of lists, convert that to a tuple and check if it is not there in the set.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497