Solve Typeerror: unhashable type ‘list’ in Python

In python, there are many types of errors as once the code has many types of problems in which this error will come. Errors will always define which type of problem has occurred in the solution.

In this article we will go through the Typeerror: unhashable type ‘list’ and what causes this error and how to get the solution for it from some of the programs.

Let’s talk about hashable as it is a feature of python objects and this tells about hash value as if any object has hash value then we can use it as a key value in the dictionary otherwise, we can use it for addition as a set element.

Example:

{Key1:Value1, Key2:Value2, Key3:Value3}

{setObject1, setObject2, setObject3}

Now there is a problem to know which object is hashable and which object is not. The objects in python which are immutable and have a hash value are called hashable and which are mutable and don’t have a hash value are called unhashable. Immutable are those which cannot be modified as a number, string, and tuple ex: num = 63, answer = ’bye’.

Mutable are those which can be modified as a list, dictionary ex: set = [2, 3, 4, 5] {1:5,2:10,3:15}

So unhashable doesn’t have a hash value so we cannot use it as a key in the dictionary or cannot add an element in the set.

Reasons for Error

Case 1:

Suppose we are taking a list of numbers and now trying to find out the hash value of the list.

numbers={23,45,[34,27],35}
print(numbers)

Now we are trying to find hash value for the set and when are printing the value the error occurs as the hash value is not coming so we cannot use it as a key in the dictionary in the set.

Traceback (most recent call last):
  File "c:\Users\91930\Documents\work\article2.py", line 1, in <module>
    numbers={23,45,[34,27],35}
TypeError: unhashable type: 'list'

So to avoid this error by removing the mutable object or replacing it with some immutable object and your code will run properly. The set or dictionary will use a hash statement for the storage of elements. A particular hashcode is being given to the set. The list is mutable so we can do implementation on the list at any time in the code and it will give unhashable value.

Case 2:

Suppose we are taking the employees and finding their marks of training to decide the promotion and we are taking the information in the dictionary.

employee = [
	{ "name": "Tom", "marks": [44, 62, 95] },
	{ "name": "Peter", "marks": [87, 98, 53] },
	{ "name": "Gwen", "marks": [72, 54, 41] }
]
best_employee = {}
for e in employee:
		 avg_marks = sum(e["marks"]) / len(e["marks"])
		 if avg_marks > 45:
		         best_employee[e["marks"]] =e["name"]
		         
print(best_employee)

Now we are running the program and it is returning back an error that the list cannot be hashable and we cannot get the hash value.

Traceback (most recent call last):
  File "<string>", line 12, in <module>
TypeError: unhashable type: 'list'

Solutions for Error

Case 1:

To solve this error we will convert the list into a hashable object as hashable objects are immutable and we cannot modify it later. So we will convert the list into a tuple then we can use it as a key for a particular set. Then we will get the hash value of the list and the error will be solved.

Here the output is the list and we got the solution to remove the error and the revised code.

numbers={23,45,tuple([34,27]),35}
print(numbers)

Output:

{(34, 27), 35, 45, 23}

Case 2:

To solve the error we will see what comes in the error.

best_employee[e["marks"]] =e["name"]

The error has been encountered in our code as we are putting a list as a key in dict. When we are iterating this line of code then we are creating a dictionary that has a key and value as like:

{[44, 62, 95]: "Tom"}

This will be an invalid dictionary as the dictionary is telling us to know that there is a key and has its value which fails to work. To solve this problem we will use the employee name as key and marks will be the values.

best_employee[e["name"]] =e["marks"]

We have provided the marks as the values without putting them as keys.

The revised code is as:

employee = [
    { "name": "Tom", "marks": [44, 62, 95] },
    { "name": "Peter", "marks": [87, 98, 53] },
    { "name": "Gwen", "marks": [72, 54, 41] }
]
best_employee = {}
for e in employee:
         avg_marks = sum(e["marks"]) / len(e["marks"])
         if avg_marks > 45:
                 best_employee[e["name"]] =e["marks"]
                 
print(best_employee)

Output:

{'Tom': [44, 62, 95], 'Peter': [87, 98, 53], 'Gwen': [72, 54, 41]}

Our code is now working properly without having any error as the employees name will be in the dictionary whose average marks above 45.

Conclusion

The TypeError: unhashable type ’list’ error has occurred when we are trying to give the list as a key in the dictionary and as the list is mutable so we can modify it and it will provide unhashashble value and the error occurs. When we want a hash value then the objects should be immutable then we will get hashable objects. Hashing we want to know about it as the method of converting the data to a similar size of integer which will only give the perfect value and we can only hash the elements which are hashable.

To solve this error we are assigning a hashable object instead of the unhashable object such as a tuple for the list so that the list can give the output. Another solution for adding a list in a dictionary is by storing it as a value. We will be meeting many problems later if we are passing values as a list so better to pass the values as strings, tuples, etc. string, tuples are immutable and we cannot modify them later. For a better version for passing a string without an error, we will pass it as a tuple and then we are seeing the hash value for it and a better conversion begins with it.

Leave a Comment

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