TypePython Error

TypeError

TypeError: unhashable type: 'list'

Traceback

terminal
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

Broken
cache = {}
key = [1, 2, 3]
cache[key] = "value"

Fixed code

Fixed
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

1

Performing operations between incompatible types like strings and integers

2

Calling methods that return None and chaining operations on the result

3

Passing the wrong number or type of arguments to a function

4

Using bracket notation on objects that do not support indexing

Related errors