πŸ”§ Error Fixes
Β· 1 min read

Python TypeError: Unhashable Type 'list' β€” How to Fix It


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: Python AttributeError fix Β· Python AssertionError fix

πŸ“˜