I have listA=[[0,1,2]], and listB=[[0,1,2],[0,1,3],[0,2,3]], and want to obtain elements that are in listB but not in listA, i.e., my desired output is listC=[[0,1,3],[0,2,3]].
I already got listC using list comprehension:
listA=[[0,1,2]]
listB=[[0,1,2],[0,1,3],[0,2,3]]
listC=[b for b in listB if b not in listA]
But if I want to do it in another way, i.e., using setdifference in the following code, I got the error message unhashable type:’list’.
listA=[[0,1,2]]
listB=[[0,1,2],[0,1,3],[0,2,3]]
listC=list(set(listB)-set(listA))
Why does this error pop up? And how it could be fixed? Thanks!
>Solution :
sets require to hash the objects, and lists are not hashable (as they are mutable).
Thus you need to convert to tuple and back to list:
listA=[[0,1,2]]
listB=[[0,1,2],[0,1,3],[0,2,3]]
listC=list(map(list,set(map(tuple,listB))-set(map(tuple,listA))))
listC
output: [[0, 1, 3], [0, 2, 3]]