Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In python, why do I get an error message of " unhashable type:'list'" when doing list(set(listB)-set(listA))?

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’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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]]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading