TypeError_ unhashable type_ 'list'

TypeError: unhashable type: ‘list’ – How to Fix it Easily?

TypeError: unhashable type: ‘list’ error occurs mainly when we use any list as a hash object. As you already know list is a mutable Python object. For hashing an object it must be immutable like tuple etc. Hence converting every mutable object into immutable is the fix for the error TypeError: unhashable type: ‘list’.

There are a few python objects which are not hashable like dict, list, byte array, set, user-defined classes, etc.  When any of these objects come at the place where we treat them as a hashable object this error occurs.  This article will show you different scenarios for this bug with their fix.

 

TypeError: unhashable type: ‘list’ –

let’s see a common scenario for this error.

Case 1: List as a dictionary key –

In order to demonstrate, We will create a dummy_dict. We can reproduce this error when we use any list a key in the dummy_dict. See the below example.

TypeError unhashable type list in dict
TypeError unhashable type list dict

 

The fix for the above error is to convert( typecasting) the list into the tuple and insert it into the dict as the key. A tuple is an immutable object. Let’s see the above code after fixing it.

 

sample_list=["C","D"]
dummy_dict={
    "A": 1,
    "B":2,
    tuple(sample_list):3

}
print(dummy_dict)

Here is the output.

{'A': 1, 'B': 2, ('C', 'D'): 3}

 

Case 2: Converting a nested list into the set –

When we typecast a nested list object directly into the set object. This error occurs.

unhashable type nested list into set
unhashable type nested list into a set

 

Like above, We can convert the nested list into the tuple. After it, we can easily convert the outer list into a set python object. Refer to the below code for better understanding.

 a = [11,23,34,tuple([51,65]),89]
 set(a)

below is the output for the code.

{(51, 65), 11, 23, 34, 89}

Case 3: Using hash() function with unhashable objects –

As you know that dict, list, byte array, set, user-defined classes, etc are unhashable objects in python. When we try to use them as a parameter in the hash function. We get the same error.

hash() function with unhashable object
hash() function with unhashable object

 

We can get the correct hash value of the above object by converting the list into the tuple object.

hash(tuple([1,2,3]))

Here is the hash value of the object after the conversion.

2528502973977326415

 

Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner