1

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'
DougKruger
  • 4,424
  • 14
  • 41
  • 62

4 Answers4

1

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))
gowrath
  • 3,136
  • 2
  • 17
  • 32
  • I got this. `TypeError: 'list' object is not callable`. A and B are both list of lists – DougKruger Aug 29 '16 at 08:44
  • @DougKruger You probably have a variable actually named "list" somewhere in your program which is overriding the builtin list function! Look through your code and if you have a variable by the name "list", change that name to something else. – gowrath Aug 29 '16 at 08:52
  • @DougKruger Or use the first version. But note there is probably a bug in your program if you have called something in your program "list". – gowrath Aug 29 '16 at 08:55
1
>>> [i for i in A if i not in B]
[[1, 2], [5, 6]]
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
1

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)
Israel Unterman
  • 13,158
  • 4
  • 28
  • 35
1
A = [[1, 2], [3, 4], [5, 6]]
B = [[3, 4], [7, 8]]

print[x for x in A if x not in B]
BPL
  • 9,632
  • 9
  • 59
  • 117