TypeError
TypeError: unhashable type: 'list'
Traceback
Traceback (most recent call last):
File "main.py", line 3, in <module>
cache[key] = "value"
TypeError: unhashable type: 'list'What causes this error
A mutable object (list, dict, or set) was used in a context requiring a hashable object — as a dictionary key, set element, or in set operations.
How to fix it
Convert lists to tuples, sets to frozensets before using as dict keys or set members. Implement __hash__ for custom classes used as keys. Use immutable data structures.
Code that causes this error
cache = {}
key = [1, 2, 3]
cache[key] = "value"Fixed code
cache = {}
key = tuple([1, 2, 3])
cache[key] = "value"About TypeError
This TypeError occurs when you try to use a mutable (unhashable) object as a dictionary key, set element, or in any other context requiring a hashable object. In Python, hashable objects must have a `__hash__` method and their hash value must never change. Mutable types like lists, dictionaries, and sets are not hashable because their content can change, which would change their hash value.
Common triggers include using a list as a dict key, adding a list to a set, and using a list in a set operation like intersection or union. The fix is to convert the mutable type to an immutable equivalent: list → tuple, dict → frozenset of items (for simple cases), set → frozenset. For complex objects used as keys, implement __hash__ and __eq__ methods or use named tuples.
Common scenarios
Performing operations between incompatible types like strings and integers
Calling methods that return None and chaining operations on the result
Passing the wrong number or type of arguments to a function
Using bracket notation on objects that do not support indexing