close

[Solved] How to overcome TypeError: unhashable type: ‘list’

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error How to overcome TypeError: unhashable type: ‘list’ 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 to overcome TypeError: unhashable type: ‘list’ Error Occurs?

Today I get the following error How to overcome TypeError: unhashable type: ‘list’ in python.

How To Solve overcome TypeError: unhashable type: ‘list’ Error ?

  1. How To Solve overcome TypeError: unhashable type: 'list' Error ?

    To Solve overcome TypeError: unhashable type: 'list' Error You're trying to use k (which is a list) as a key for d. Lists are mutable and can't be used as dict keys.

  2. How to overcome TypeError: unhashable type: 'list'

    To Solve overcome TypeError: unhashable type: 'list' Error You're trying to use k (which is a list) as a key for d. Lists are mutable and can't be used as dict keys.

Solution 1


Note:
 This answer does not explicitly answer the asked question. the other answers do it. Since the question is specific to a scenario and the raised exception is general, This answer points to the general case.

Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly.

Internally, hash() method calls __hash__() method of an object which are set by default for any object.

Converting a nested list to a set

>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

This happens because of the list inside a list which is a list which cannot be hashed. Which can be solved by converting the internal nested lists to a tuple,

>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])

Explicitly hashing a nested list

>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506

The solution to avoid this error is to restructure the list to have nested tuples instead of lists.

Solution 2

You’re trying to use k (which is a list) as a key for d. Lists are mutable and can’t be used as dict keys.

Also, you’re never initializing the lists in the dictionary, because of this line:

if k not in d == False:

Which should be:

if k not in d == True:

Which should actually be:

if k not in d:

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