How To Resolve TypeError: Unhashable Type: ‘list’ In Python

TypeError: unhashable type: ‘list’

You cannot use a list as a hash argument, it will results in an error TypeError: unhashable type: ‘list’. Please read the following article to be able to resolve the error.

What causes the “TypeError: unhashable type: ‘list'” error?

What is a list in Python?

In Python, a list is a sequence of values. In the string data type, the values are characters. Whereas with list type, values can have any call data type. Each value in the list is called an element.

What is hashable?

‘Hashable’ is a feature in Python used to determine if an object has a hash value. An object is hashable if it has a hash value for the duration of its existence. A hash value is a key for a dictionary or an element of a set.

The error “TypeError: unhashable type: ‘list'” happens when you use a list as a hash argument; however, the list is an immutable object that results in an error.

Example: 

student = {"name": "John", [9, 10]: 'grades'}
print(student)

Output:

Traceback (most recent call last):
  File "prog.py", line 1, in <module>
    student = {"name": "John", [9, 10]: 'grades'}
TypeError: unhashable type: 'list'

This error shows that the key of ‘student’ dictionary [9, 10] is a list, which is not hashable.

How to solve this error?

Convert the list to a tuple

To solve this error, you would use the tuple() function to convert the list to a tuple if you want to set them as keys in the dictionary.

Syntax:

tuple(iterable)
  • iterable: objects with multiple iterable elements such as list, string, tuple, set, or iterators in python.

Example:

student = {"name": "John", tuple([9, 10]): 'grades'}
print(student)

Output:

{'name': 'John', (9, 10): 'grades'}

Use json.dumps to convert the list

To fix the error, you can use the json.dumps function to convert a list to a string

Example:

import json

gradesStr = json.dumps([9, 10])
print(type(gradesStr)) # <class 'str'>

student = {"name": "John", gradesStr: 'grades'}
print(student) # {'name': 'John', '[9, 10]': 'grades'}
{'name': 'John', '[9, 10]': 'grades'}

Summary

This article will be the solution for you if you encounter error “TypeError: unhashable type: ‘list'” in Python. If you have any questions about this issue, leave a comment below. I will answer your questions.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *