Reputation: 4624
Consider two lists A and B. I know that list(set(A) - set(B))
will give the difference between A and B. What about the situation whereby elements in both A and B are lists. i.e. A and B are list of list? For e.g.
A = [[1,2], [3,4], [5,6]]
B = [[3,4], [7,8]]
I wish to return the difference A - B
as a list of list i.e. [[1,2],[5,6]]
list(set(A) - set(B))
TypeError: unhashable type: 'list'
Upvotes: 1
Views: 64
Reputation: 13510
The idea is to convert the list of lists to lists of tuples,
which are hashable and are, thus, candidates of making sets themselves:
In [192]: C = set(map(tuple, A)) - set(map(tuple, B))
In [193]: C
Out[193]: {(1, 2), (5, 6)}
And one more touch:
In [196]: [*map(list, C)]
Out[196]: [[1, 2], [5, 6]]
ADDED
In python 2.7 the final touch is simpler:
map(list, C)
Upvotes: 1
Reputation: 9863
A = [[1, 2], [3, 4], [5, 6]]
B = [[3, 4], [7, 8]]
print[x for x in A if x not in B]
Upvotes: 1
Reputation: 3224
Here's a one-liner you could use:
diff = [x for x in A if x not in B]
Or if you want to use filter:
diff = list(filter(lambda x: x not in B, A))
Upvotes: 1