Skip to main content

Solve Typeerror: unhashable type ‘list’ in Python Gorakh Gupta The Crazy Programmer

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.

The post Solve Typeerror: unhashable type ‘list’ in Python appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/WCtavsr

Comments

Popular posts from this blog

Difference between Web Designer and Web Developer Neeraj Mishra The Crazy Programmer

Have you ever wondered about the distinctions between web developers’ and web designers’ duties and obligations? You’re not alone! Many people have trouble distinguishing between these two. Although they collaborate to publish new websites on the internet, web developers and web designers play very different roles. To put these job possibilities into perspective, consider the construction of a house. To create a vision for the house, including the visual components, the space planning and layout, the materials, and the overall appearance and sense of the space, you need an architect. That said, to translate an idea into a building, you need construction professionals to take those architectural drawings and put them into practice. Image Source In a similar vein, web development and design work together to create websites. Let’s examine the major responsibilities and distinctions between web developers and web designers. Let’s get going, shall we? What Does a Web Designer Do?

A guide to data integration tools

CData Software is a leader in data access and connectivity solutions. It specializes in the development of data drivers and data access technologies for real-time access to online or on-premise applications, databases and web APIs. The company is focused on bringing data connectivity capabilities natively into tools organizations already use. It also features ETL/ELT solutions, enterprise connectors, and data visualization. Matillion ’s data transformation software empowers customers to extract data from a wide number of sources, load it into their chosen cloud data warehouse (CDW) and transform that data from its siloed source state, into analytics-ready insights – prepared for advanced analytics, machine learning, and artificial intelligence use cases. Only Matillion is purpose-built for Snowflake, Amazon Redshift, Google BigQuery, and Microsoft Azure, enabling businesses to achieve new levels of simplicity, speed, scale, and savings. Trusted by companies of all sizes to meet

2022: The year of hybrid work

Remote work was once considered a luxury to many, but in 2020, it became a necessity for a large portion of the workforce, as the scary and unknown COVID-19 virus sickened and even took the lives of so many people around the world.  Some workers were able to thrive in a remote setting, while others felt isolated and struggled to keep up a balance between their work and home lives. Last year saw the availability of life-saving vaccines, so companies were able to start having the conversation about what to do next. Should they keep everyone remote? Should they go back to working in the office full time? Or should they do something in between? Enter hybrid work, which offers a mix of the two. A Fall 2021 study conducted by Google revealed that over 75% of survey respondents expect hybrid work to become a standard practice within their organization within the next three years.  Thus, two years after the world abruptly shifted to widespread adoption of remote work, we are declaring 20