TypeError: unhashable type: 'list'
Youβre trying to use a list as a dictionary key or in a set. Lists are mutable, so Python canβt hash them.
Why this happens
Python dictionaries and sets use hash tables internally. Every key or set member must be hashable β meaning it has a fixed hash value for its lifetime. Lists are mutable, so their contents can change after insertion, which would break the hash table. Python prevents this by refusing to hash lists at all.
Fix 1: Use a tuple instead
# β Lists can't be dict keys or set members
my_dict = {[1, 2]: "value"} # TypeError!
# β
Use tuples (immutable)
my_dict = {(1, 2): "value"}
my_set = {(1, 2), (3, 4)}
Fix 2: Convert list to tuple for sets
items = [[1, 2], [3, 4], [1, 2]]
# β
Convert to tuples
unique = set(tuple(item) for item in items)
# {(1, 2), (3, 4)}
Fix 3: Use frozenset for sets of sets
# β Sets can't contain sets
s = {{"a", "b"}, {"c", "d"}} # TypeError!
# β
Use frozenset
s = {frozenset({"a", "b"}), frozenset({"c", "d"})}
Alternative solutions
If you need list-like keys for grouping, convert to a string representation:
from collections import defaultdict
groups = defaultdict(list)
for item in data:
key = str(sorted(item))
groups[key].append(item)
Prevention
- When building data structures, ask: βWill this be a dict key or set member?β If yes, use tuples from the start.
- Use type hints like
dict[tuple[int, ...], str]to catch these issues with a type checker before runtime.
Related resources
Related: Python AttributeError fix Β· Python AssertionError fix