If you’ve been working with the Python programming language for any amount of time, you’ve likely seen your fair share of errors when coding. A common error that pops up is the TypeError: Unhashable Type: ‘List’ error, which arises when you attempt to hash an object that is unhashable in Python. While this can be confusing and frustrating, we’ll explain below what this error means and how to fix it. Let’s get started.
What is a Python dictionary?
In Python 3.8, a dictionary is a collection of ordered and mutable key to value pairings that map unique keys to specific values. In previous versions of Python (3.6 or earlier), these dictionary keys were ordered and immutable, meaning that you could not change them once they were created.
An example of dictionary key-value pairing
A dictionary pairing is written with curly brackets, and it includes the key-value pairings separated by commas. A colon is used to separate the key from its value.
Here is a Python dictionary containing the population of Canada’s three largest cities:
population = {'Toronto': 6200000, 'Montreal': 4200000, 'Vancouver': 2600000}
Why are dictionaries useful?
This style of data structure is useful since it allows you to generate keys that act as a label for a value, allowing you to quickly access a specific value by referring to the key name you want to retrieve.
What is hashability?
When we talk about hashability, what we are referring to is whether a piece of data has the property of “hashability” or, in other words, the ability for it to be used as a key in a Python dictionary. While coding with Python, you will find two data types, one that is hashable and one that is unhashable.
- A hashable data type is a value that remains constant throughout. Data types that fall into this category include int, float, decimal, bool, string, tuple, complex, range, and bytes.
- An unhashable data type is a value that does not remain constant and can have its state changed after creation. Data types that fall into this category include lists, dictionaries (dict), sets, custom classes, and bytearray.
Data types or objects that fall under the unhashable category cannot work as keys because changing them would affect hashing algorithms that rely on unique data points for each object/key pairing within dictionaries. Therefore, if you tried to use them in your coding as hashable, you would get the TypeError: Unhashable Type: ‘List’ error.
Three examples of the TypeError: Unhashable Type: ‘List’ error
Below are a few examples of when you may encounter the TypeError: Unhashable Type: ‘List’ error.
- When you try to put a list in a set or as a key in a dictionary and then attempt to print it. This won’t work because a list is an unhashable object.
- When you try to typecast a nested list object directly into a set object using the set() function.
- When you try to use the hash() function with an unhashable object such as a nested list.
How to fix the Python TypeError: Unhashable Type: ‘List’ error
Now that we know what causes this error and some example scenarios of when it will occur, let’s take a look at what the error looks like in code and how to go about fixing it.
1. Adding a list to a set or as a key in a dictionary
Suppose you tried to add a list as a key in a dictionary as per below:
dict1 = { 1:’one’, [2,10]:’two’}
print(dict1)
You would get the following output error:
A similar output when trying to add a list to a set:
You can resolve these coding mistakes by casting the list to a tuple, as a tuple can be used as a key in the Python dictionary since it is an immutable object. A tuple is a collection that is ordered, unchangeable, and allows for duplicate members.
Here is how to cast a list to a tuple in a dictionary:
dict1 = { 1:’one’, tuple([2,10]):’two’}
print(dict1)
Here is how to cast a list to a tuple in a set:
set1 = {tuple([1,2]),tuple([3,4])}
print(set1)
2. Converting a nested list object directly into a set using set()
When you try to convert a nested list object directly into a set object, you’re going to get the TypeError: Unhashable Type: ‘List’ error. Here is what this looks like:
a = [11,23,34,[51,65],89]
set(a)
The output will be TypeError: unhashable type: ‘list’:
For this, you would use a tuple like in the first solution. You would rewrite the code as follows:
a = [11, 23, 34, tuple ([51, 65]), 89]
set (a)
Now you will get a valid output: { (51, 65), 11, 23, 34, 89}
3. Using the hash function
When you try to use the hash function on an unhashable object in Python, you also get the TypeError: Unhashable Type: ‘List’ error.
Here is what this looks like with an incorrect code:
hash([1,2,3])
The output is a TypeError:
To get the right hash value, you can convert the list into a tuple to receive the right conversion. The coding for this is very similar to the other solutions listed above:
hash (tuple ([1,2,3]))
After the code change, you will get the right conversion of 2528502973977326415.
Fixing the TypeError: Unhashable Type: ‘List’ error in Pandas
If you are working with Pandas, an open source Python data analysis and manipulation tool that is built to work on top of the Python programming language, you may run into the TypeError: Unhashable Type: ‘List’ error when working with operations like value_counts, groupby, and transform.
When you apply these operations against a column of type ‘dict’ or ‘list,’ you end up with the TypeError: Unhashable Type: ‘List’ error. To solve this, you will need to:
- Detect to see if a column contains a list or a dict and if it does, convert the column to a string and apply your value_counts or groupby after that.
- You can also convert the list or dict column to a tuple and then apply your operations to it.
- Or, you can expand the list column so that the column contains a stored list and not a string.
Wrapping It Up
What did you do to solve the TypeError: Unhashable Type: ‘List’ error in your use case? Let us know in the comments if any of the information in this blog post helped you out.
A special thanks goes out to all of our readers who engage with us, either by reading our posts, leaving comments, or working with us to provide easy-to-understand answers to our growing community.