Chances are you have run through this error when you tried using a list as a dictionary key or added it to a set, in Python. It looks confusing at first, but it isn’t as complicated as it might appear. Today we will understand why this error occurs, and how to fix it with ease.

Why This Error Happens

In Python, dictionary keys and set elements must be hashable. That means:

  • They have a fixed hash value.
  • They can be compared to other objects.
  • They are not supposed to change (they’re immutable).

A list can be changed at any time, which means its value isn’t stable. Because of that, Python doesn’t allow lists to be used as dictionary keys or set elements. It needs something that stays the same, like a tuple.

Here’s what causes the error:

my_dict = {[1, 2, 3]: "numbers"}

Output:

TypeError: unhashable type: 'list'

Or maybe:

my_set = set()
my_set.add([1, 2, 3])

Steps to Resolve the Issue

Step 1: Use a Tuple Instead of a List

If your list is just a collection of values and doesn’t need to change, convert it to a tuple:

my_dict = {(1, 2, 3): "numbers"} # ✅ No error
my_set = set()
my_set.add((1, 2, 3)) # ✅ Works

Tuples are immutable and hashable if all their elements are hashable.

Step 2: Avoid Mutable Keys

Never use mutable types (like lists or dicts) as keys in dictionaries or elements in sets.

Bad:

my_dict = {[1, 2]: "value"}

Good:

my_dict = {tuple([1, 2]): "value"}

Step 3: If You Need Mutability, Use frozenset or Custom Classes

If your data is inherently set-like but needs to be hashable, use frozenset:

my_set = set()
my_set.add(frozenset([1, 2, 3])) # ✅ Works

You can also define your own class with custom __hash__ and __eq__ if advanced control is needed.

Step 4: Revisit Your Data Structure Design

Ask yourself: do I really need to use a list here?

  • If yes, maybe switch to another structure (e.g., list of dicts, nested dicts)
  • If not, replace with a tuple or string depending on the use case

To Conclude

To put it simply, you get this error because lists can change, and Python only allows unchangeable (hashable) types as dictionary keys or set elements. If you need to use list-like data in those places, try using a tuple or frozenset instead. And if you’re unsure about the best structure for your data, it might help to hire Python developers who can guide you in building a cleaner, more reliable solution.