Python TypeError

Python TypeError: unhashable type 'list' — Causes & Fix

Python TypeError: unhashable type 'list' — list as dict key fix

What Does This Error Mean?

Python raises TypeError: unhashable type: 'list' when you try to use a list as a dictionary key or as a set element. Hashing requires the object to be immutable — lists are mutable, so they have no hash value and cannot be used in these contexts.

Common Causes (With Code)

1. Using a list as a dictionary key

❌ Causes the error

my_dict = {}
key = [1, 2, 3]           # list is mutable — no hash
my_dict[key] = "value"
# TypeError: unhashable type: 'list'

2. Adding a list to a set

❌ Causes the error

my_set = {[1, 2], [3, 4]}
# TypeError: unhashable type: 'list'

my_set = set()
my_set.add([1, 2, 3])
# TypeError: unhashable type: 'list'

3. Using a list inside a set comprehension or as a Counter key

❌ Causes the error

from collections import Counter
data = [[1, 2], [1, 2], [3, 4]]
Counter(data)   # TypeError: unhashable type: 'list'

How to Fix It

Fix 1 — Convert the list to a tuple (immutable)

✅ Correct

my_dict = {}
key = (1, 2, 3)           # tuple is immutable and hashable
my_dict[key] = "value"
print(my_dict)  # {(1, 2, 3): 'value'}

Fix 2 — Use a frozenset if order doesn't matter

✅ Correct

my_set = {frozenset([1, 2]), frozenset([3, 4])}
print(my_set)   # {frozenset({1, 2}), frozenset({3, 4})}

Fix 3 — Convert lists to tuples before counting

✅ Correct

from collections import Counter
data = [[1, 2], [1, 2], [3, 4]]
Counter(tuple(item) for item in data)
# Counter({(1, 2): 2, (3, 4): 1})

Frequently Asked Questions

Can I use a list as a dictionary value?

Yes — lists are perfectly valid as dictionary values. The restriction only applies to dictionary keys and set elements, which require hashing.

d = {"key": [1, 2, 3]}   # ✅ This is fine
print(d["key"])           # [1, 2, 3]

Why are tuples hashable but lists are not?

Tuples are immutable — once created, their contents cannot change. Python can compute a stable hash for them. Lists are mutable, so their hash could change mid-execution, breaking dictionary and set internals.