In this post, we will see about TypeError: unhashable type: 'list'.
You will get this error when you are trying to put list as key in dictionary or set because list is unhashable object.TypeError: unhashable type is generally raised when you try to hash object which is unhashable.
Let’s see this with help of example:
dict1 ={ 1:'one', [2,10]:'two'}
print(dict1)
Output:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last)in ----> 1 dict1 ={ 1:'one', [2,10]:'two'} 2 print(dict1) TypeError: unhashable type: 'list'
You can resolve this issue by casting list to tuple. Since tuple is immutable object, it can be used as key in dictionary.
dict1 ={ 1:'one', tuple([2,10]):'two'}
print(dict1)
Output:
As you can see, once we use tuple() function, program worked fine.
Let’s see another example with set.
set1={[1,2],[3,4]}
print(set1)
Output:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last)in ----> 1 set1={[1,2],[3,4]} TypeError: unhashable type: 'list'
You can resolve this issue by casting list to tuple. Since tuple is immutable object, it can be used as key in dictionary.
set1={tuple([1,2]),tuple([3,4])}
print(set1)
Output:
As you can see, once we use tuple() function, program worked fine.
What are Hashable objects?
Hashing is a method of encoding data into fixed-size int value. It is generally used to design high performing data structure.
Hashable object in Python
[table id=23 /]
Non Hashable object in Python
[table id=24 /]
That’s all about TypeError: unhashable type: ‘list’.