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:
1 2 3 4 |
dict1 ={ 1:'one', [2,10]:'two'} print(dict1) |
Output:
1 2 3 4 5 6 7 8 9 10 |
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-73-c4e2fd1e6bf0> in <module> ----> 1 dict1 ={ 1:'one', [2,10]:'two'} 2 print(dict1) TypeError: unhashable type: 'list' </module></ipython-input-73-c4e2fd1e6bf0> |
You can resolve this issue by casting list to tuple. Since tuple is immutable object, it can be used as key in dictionary.
1 2 3 4 |
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.
1 2 3 4 |
set1={[1,2],[3,4]} print(set1) |
Output:
1 2 3 4 5 6 7 8 9 |
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-75-31a9df7b7b7f> in <module> ----> 1 set1={[1,2],[3,4]} TypeError: unhashable type: 'list' </module></ipython-input-75-31a9df7b7b7f> |
You can resolve this issue by casting list to tuple. Since tuple
is immutable object, it can be used as key in dictionary.
1 2 3 4 |
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
int | float | decimal | bool | string | tuple | complex | range | frozenset | bytes |
Non Hashable object in Python
list | set | dict | bytearray | custom classes |
That’s all about TypeError: unhashable type: ‘list’.