Hey, fellow coders! Have you ever encountered this annoying error message: typeerror: unhashable type: ‘list’? If you have, you know how frustrating debugging can be. In this blog post, I’ll explain what causes this error and how to fix it.
What does the error mean?
The unhashable type: ‘list’ type error occurs when you try to use a list as a key in a dictionary or a set, or when you try to hash a list using the built-in hash function.
A key is a value that uniquely identifies an entry in a dictionary or a set.
For example, in the dictionary {'name': 'Alice', 'age': 25}
, the keys are 'name'
and 'age'
. Keys must be hashable, which means they have a fixed value that can be used to calculate a unique number called a hash. The hash is used to store and retrieve the entries efficiently.
Lists are not hashable because they are mutable, which means they can change their value over time. For example, you can append, insert, or remove elements from a list. This means that their hash value can also change, making them unsuitable for use as keys. If you try to use a list as a key, Python will raise the TypeError: unhashable type: 'list'
.
What does unhashable mean?
First of all, what does unhashable mean?
A hashable object is one that can be used as a key in a dictionary or a set. A hashable object must have a __hash__ method that returns a unique integer value for the object, and an __eq__ method that compares the object with another object for equality. A list is not hashable because it is mutable, meaning it can change its contents. Therefore, it does not have a consistent hash value or a reliable way to compare it with other objects.
Why does Python raise the Typeerror: unhashable type: ‘list’
So, why does Python raise a typeerror when you try to use a list as a key? Well, Python uses hashing to optimize the lookup of keys in dictionaries and sets. If you use an unhashable object as a key, Python cannot find it in the hash table which raises an exception. This is to prevent you from creating inconsistent or corrupted data structures.
Examples of the unhashable type: ‘list’ error
Here are some examples of code snippets that may produce the error:
# Trying to use a list as a key in a dictionary
my_dict = {[1, 2, 3]: 'a', [4, 5, 6]: 'b'}
# TypeError: unhashable type: 'list'
# Trying to use a list as a key in a set
my_set = set([[1, 2, 3], [4, 5, 6]])
# TypeError: unhashable type: 'list'
# Trying to use a list as an element in a set
my_set = set([1, 2, 3, [4, 5, 6]])
# TypeError: unhashable type: 'list'
How to Fix & Avoid the unhashable type: ‘list’ error
There are several ways to fix this error, depending on your specific situation and needs. Here are some possible solutions:
Use a tuple instead of a list:
The simplest solution is to convert the list to a tuple using tuple(list_name)
. Tuples are immutable and have a fixed hash value, making them suitable for keys. For example:
my_dict = {(1, 2, 3): 'a', (4, 5, 6): 'b'} # No error
my_set = set([(1, 2, 3), (4, 5, 6)]) # No error
my_set = set([1, 2, 3, (4, 5, 6)]) # No error
Use a different data structure:
If you need to keep the order of elements, consider using a namedtuple or a custom class with a __hash__
method defined.
These are user-defined types that can have attributes and methods like regular classes, but also behave like tuples in terms of immutability and hashing. If order is not important, a set might be a better choice than a list.
Sets are collections of unique and hashable elements that support fast membership testing and set operations.
example of using a namedtuple:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
point = Point(1, 2)
my_set = {point} # Correct!
example of using a custom class with a __hash__
method:
class HashableList:
def __init__(self, data):
self.data = data
def __hash__(self):
return hash(tuple(self.data))
list_key = HashableList([1, 2, 3])
my_dict[list_key] = "Value" # Correct!
Use a different approach:
If the error arises from a specific operation, consider if there’s a different way to achieve the same result without using a list as a key. For example, if you want to count the frequency of elements in a list, you can use the Counter class from the collections module instead of creating your own dictionary.
I hope this blog post helped you understand the typeerror: unhashable type: ‘list’ and how to fix it. If you have any questions or comments, feel free to leave them below. Happy coding!