Register Login

TypeError: unhashable type: 'list'

Updated Dec 18, 2019

Error: TypeError unhashable type 'list'

This error occurs when you try to use a list as key in the dictionary or set. As you know 'list' is an unhashable object that can not be used as a key for any dictionary or set.

In simple terms, this error occurs when you try to hash a 'list', which is an unhashable object.

TypeError: unhashable type: 'list'

Example 1: Using 'list' as key in a dictionary

my_dictionary = {'Red':'Apple','Green':'Mango',[1,2,3]:'Banana'}
print('Dictionary :',my_dictionary)

Output:

TypeError: unhashable type: 'list'

Solution

To fix this error, you can convert the 'list' into a hashable object like 'tuple' and then use it as a key for a dictionary as shown below

Correct Code

my_dictionary = {'Red':'Apple','Green':'Mango',tuple([1,2,3]):'Banana'}
print('Dictionary :',my_dictionary)

Output:

Dictionary : {'Red': 'Apple', 'Green': 'Mango', (1, 2, 3): 'Banana'}

TypeError unhashable type list Solve

Example 2: Using list as key in a set

mylist = [1,2,[3,4],5,6,7,8,9]
myset = set(mylist)
print('Set :',myset)

Output:

TypeError: unhashable type: 'list'

Solution

To fix this error, you can convert the 'list' into a hashable object like tuple then use it as a key for 'set' as shown below:

Correct Code

mylist = [1,2,tuple([3,4]),5,6,7,8,9]
myset = set(mylist)
print('Set :',myset)

Output:

Set : {1, 2, 5, 6, 7, 8, 9, (3, 4)}

What is Hashing in Python

In python, hashing is the method of encoding the data into a fixed-size integer which represent the original value. You can hash only those objects which are hashable or objects that can't be altered.

Hashable objects in Python

int, float, decimal, complex, bool, string, tuple, range, frozenset, bytes

Unhashable objects in Python

list, dict, set, bytearray, user-defined classes


×