Friday, September 22, 2017

[Python][Resolved] TypeError: unhashable type: 'list'

 I want to convert a 2 dimensional list to a set with set(), but it got a type error:
>>> list1 = [[1,2,3],[2,5,6],[7,8,9]]
>>> type(list1)
<class 'list'>
>>> set1 = set(list1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
I found it's needed to change syntax to create your list
>>> list2 = [(1,2,3),(2,5,6),(7,8,9)]
>>> type(list2)
<class 'list'>
>>> set2 = set(list2)
>>> set2
{(7, 8, 9), (2, 5, 6), (1, 2, 3)} 


1 comment :

  1. The hash() is a built-in python method, used to return a unique number . This can be applied to any user-defined object which won’t get changed once initialized. This property is used mainly in dictionary keys .

    TypeError: unhashable type: 'list' usually means that you are trying to use a list as an hash argument. This means that when you try to hash an unhashable object it will result an error. For ex. when you use a list as a key in the dictionary , this cannot be done because lists can't be hashed. The standard way to solve this issue is to cast a list to a tuple .

    ReplyDelete