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
  • 3,874
  • 11
  • 37
  • 57

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
  • 2,856
  • 2
  • 16
  • 31
  • 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
  • 9,865
  • 4
  • 35
  • 51
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
  • 12,444
  • 3
  • 26
  • 34
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,532
  • 7
  • 47
  • 105