close

[Solved] TypeError : Unhashable type

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error TypeError : Unhashable type in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How TypeError : Unhashable type Error Occurs?

Today I get the following error TypeError : Unhashable type in python.

How To Solve TypeError : Unhashable type Error ?

  1. How To Solve TypeError : Unhashable type Error ?

    To Solve TypeError : Unhashable type Error A list is unhashable because its contents can change over its lifetime. You can update an item contained in the list at any time.

  2. TypeError : Unhashable type

    To Solve TypeError : Unhashable type Error A list is unhashable because its contents can change over its lifetime. You can update an item contained in the list at any time.

Solution 1


You are creating a set via set(...) call, and set needs hashable items. You can’t have set of lists. Because list’s arent hashable.

[[(a,b) for a in range(3)] for b in range(3)] is a list. It’s not a hashable type. The __hash__ you saw in dir(…) isn’t a method, it’s just None.

A list comprehension returns a list, you don’t need to explicitly use list there, just use:

>>> [[(a,b) for a in range(3)] for b in range(3)]
[[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]

Try those:

>>> a = {1, 2, 3}
>>> b= [1, 2, 3]
>>> type(a)
<class 'set'>
>>> type(b)
<class 'list'>
>>> {1, 2, []}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> print([].__hash__)
None
>>> [[],[],[]] #list of lists
[[], [], []]
>>> {[], [], []} #set of lists
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Solution 2


A list is unhashable because its contents can change over its lifetime. You can update an item contained in the list at any time.

A list doesn’t use a hash for indexing, so it isn’t restricted to hashable items.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read