TypeError: unhashable type: 'list'
What it means
You used a list as a dictionary key or as an item in a set. Python stores keys and set items by a hash worked out from their contents, and a list can change, so it has no hash. Use a tuple instead; dictionaries and sets can change too, and give the same error with 'dict' or 'set'.
1. A list as a dictionary key
This raises the error
Traceback (most recent call last): File "<exec>", line 3, in <module> TypeError: unhashable type: 'list'
The fix
{(3, 4): 'home'}
homeA tuple is like a list that cannot be changed, so Python can hash it. Use tuple(my_list) to convert a list you already have.
2. Putting lists in a set to remove duplicates
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: unhashable type: 'list'
The fix
{(1, 2), (3, 4)}
2 unique pairsEach inner list becomes a tuple, and tuples can go in a set. Convert back with [list(p) for p in unique] if you need lists again.
3. A dictionary inside a set
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: unhashable type: 'dict'
The fix
{7}
TrueA dictionary can change, so it cannot go in a set either. Store a simple value that identifies it, such as an id, or keep the dictionaries in a list.
When you see this error, check
- Look at the dictionary key or set item on the failing line and print its
type(). - Convert a list to a tuple with
tuple()before using it as a key. - Use
frozenset()when you need a set inside a set or as a key. - Remember that
{[1, 2]}is a set, so it also tries to hash the list.
Related errors
All Python errors · How to read a traceback · Step through your code