
Python dictionaries (dict) and sets (set) achieve $O(1)$ average lookup speed by storing every key or element in a hash table based on its integer hash value (hash(obj)). For a hash table to work reliably, an object’s hash value must never change over its lifetime. Because a Python list is mutable—you can append, remove, or modify its items in place at any time—Python intentionally disables hashing on lists (list.__hash__ is None).
Whenever you try to use a list as a dictionary key (grid[[10, 20]] = "Player"), add a list to a set (set([[1, 2], [3, 4]])), pass a list to a @lru_cache function, or run Pandas .drop_duplicates() on a column containing lists, Python immediately halts with TypeError: unhashable type: 'list'.
Reading the unhashable type: 'list' Traceback
Read the traceback from the bottom up. Python raises this error at the exact moment CPython’s internal PyObject_Hash() function is called on a list object—whether directly or buried inside a tuple, set comprehension, or Pandas hash table:
Traceback (most recent call last):
File "/var/www/app/main.py", line 2, in <module>
grid = {coords: "Player"}
TypeError: unhashable type: 'list'- Python 3.11+ Carets: Starting in Python 3.11+ (not run by me; noted from documentation), the traceback underlines the dictionary literal, set call, or subscript expression that triggered the failed hash lookup.
Tested Environment: Python 3.10.16, NumPy 1.26.3 & Pandas 2.0.0 (Linux) | Python 3.11+ carets, Python 3.12+ slice hashing, and linter/type-checker CLI outputs not run by me; noted from documentation.
Part of: The Ultimate Python Debugging Guide
⚡ The Quick Fix: Convert the list to an Immutable tuple
Because a tuple is immutable, it is hashable (as long as all of its elements are also hashable). Fix the error by converting the list into a tuple:
1. Using Coordinates or Composite Keys in a dict: Wrap in tuple()
coords = [10, 20]
# Fails: 'coords' is a mutable list
# grid = {coords: "Player"}
# Fix: Convert the list to an immutable tuple (10, 20)
grid = {tuple(coords): "Player"}
print(grid[(10, 20)]) # Prints: Player2. Deduplicating a Flat 2D List of Lists ([[1, 2], [1, 2]]) with dict.fromkeys() Calling set(rows) on a 2D list crashes because the inner elements are lists. For flat inner lists, convert each inner list to a tuple first (using dict.fromkeys() to preserve the original order):
rows = [[1, 2], [3, 4], [1, 2]] # Fails: inner elements [1, 2] are lists! # unique_rows = set(rows) # Fix 1 (Returns unique tuples, order preserved): unique_tuples = list(dict.fromkeys(tuple(r) for r in rows)) print(unique_tuples) # [(1, 2), (3, 4)] # Fix 2 (Returns unique lists, order preserved): unique_lists = [list(t) for t in dict.fromkeys(tuple(r) for r in rows)] print(unique_lists) # [[1, 2], [3, 4]]
3. Pandas .drop_duplicates() on a DataFrame with List Columns Either deduplicate only on scalar columns with subset=[...], or convert flat 1D list cells to tuples (for nested lists/dicts inside cells, use the recursive freeze_data() helper in Cause #3):
# Fix A: Ignore the list column and deduplicate by scalar ID column clean_df = df.drop_duplicates(subset=["order_id"]) # Fix B (Flat 1D lists): Convert each list cell to a tuple before drop_duplicates() clean_df = df.assign(tags=df["tags"].map(tuple)).drop_duplicates()
⏱️ The 10-Second Diagnostic: What Your TypeError: unhashable type: 'list' Looks Like
Find the pattern that matches your crashing line to grab the exact fix in under 15 seconds:
| What the Code Looks Like | Root Cause | The Exact Fix |
|---|---|---|
| d[my_list] = val (or {my_list: val}) | Dictionary keys must be immutable and hashable. | Convert key to a tuple: d[tuple(my_list)] = val |
| set(list_of_lists) (e.g., set([[1, 2], [3, 4]])) | set() hashes each inner element, and inner elements are lists. | Convert flat inner lists: {tuple(x) for x in list_of_lists} |
| seen.add(([1, 2], “a”)) (tuple containing a list) | A tuple is only hashable if every item inside it is also hashable. | Convert inner list to tuple: seen.add(((1, 2), “a”)) |
| if [1, 2] in my_set: (or my_dict.get([1, 2])) | in on a set/dict hashes the left-hand target. | Convert target to tuple: if (1, 2) in my_set: |
| my_dict[0:3] (Python < 3.12: unhashable type: ‘slice’; 3.12+: KeyError) | Used list slicing syntax [start:stop] on a dict. | Slice items view: list(my_dict.items())[:3] |
| @lru_cache function called with fn([1, 2]) | functools.lru_cache hashes all function arguments to build the cache key. | Pass a tuple fn(tuple(items)) or wrap the cached helper. |
| df.drop_duplicates() (or df.groupby(“tags”) / df[“tags”].unique()) | DataFrame column contains Python list objects in its cells. | Pass subset=[“id”] or convert flat lists with df[“tags”].map(tuple) |
Can You Fix This Dictionary Key TypeError?
coords = [10, 20] grid = {coords: "Player"} print(grid)
Choose the best fix for the dictionary key:
Table of contents
- Reading the unhashable type: ‘list’ Traceback
- ⚡ The Quick Fix: Convert the list to an Immutable tuple
- Python’s Hashability Contract, Collisions & Debugging Workflow
- Common Causes of TypeError: unhashable type: ‘list’
- 1. Using a list as a Dictionary Key (Or Passing a list to dict.get() / in )
- 2. Deduplicating a 2D List of Lists with set() or collections.Counter()
- 3. The Nested Tuple Trap: A tuple Containing a list or dict ( ([1, 2], “meta”) )
- Can You Fix This Nested Tuple Set Error?
- 4. Passing a list Argument to @functools.lru_cache or @functools.cache
- 5. Slicing a Dictionary ( my_dict[0:2] — Python < 3.12 vs. Python 3.12+)
- 6. Pandas .drop_duplicates() , .groupby() , .unique() , and .merge() on List Columns
- 7. Custom Classes Overriding __eq__ & @dataclass Parameters
- When NOT to Convert a list to a tuple (And What to Do Instead)
- Mutable vs. Immutable Counterparts (Including Dict & NumPy Caveats)
- Sibling unhashable type Error Variants
- Catch Unhashable Keys Before Runtime with Type Checkers and Linters
- Frequently Asked Questions
- Official Documentation & Related Fixes
Python’s Hashability Contract, Collisions & Debugging Workflow
The Python Hashability Contract (And How Hash Collisions Work)
When you insert a key into a dict or an item into a set, CPython calls the built-in hash(obj) function (PyObject_Hash at the C level). To participate safely in a hash table, every hashable object in Python must obey a strict two-part Hashability Contract:
- Hash Stability (Immutability Over Lifetime): An object’s hash value (
hash(a)) must never change during its lifetime. - Equality Implies Equal Hashes: If two objects compare equal (
a == b), they must have the exact same hash (hash(a) == hash(b)).
💡 How Hash Collisions and Table Slots Work: Notice that the contract is one-way: a == b requires hash(a) == hash(b), but two unequal objects are allowed to produce the same hash integer (a hash collision) or map to the same table slot (an index collision). Under the hood, a CPython dictionary or set with $2^k$ slots (for example, 8 slots indexed 0 through 7) computes a key’s initial slot index by masking the lower bits of the hash: slot = hash(key) & (table_size - 1). For instance, in CPython (verified on 3.10.16), hash(-1) and hash(-2) both return -2 (because -1 is reserved internally as CPython’s C-level error return value). In an 8-slot table, both -1 and -2 map to initial slot -2 & 7 == 6. When inserting -2 into {-1: "a", -2: "b"}, Python sees slot 6 is occupied, checks whether the existing key equals the new key (-1 == -2, which is False), and uses open-addressing perturbation probing to store -2 in the next available slot.
Why Mutable Lists Are Blocked (__hash__ = None):
When a class defines value-based equality (__eq__) and allows in-place mutation (list, dict, set, bytearray), Python explicitly sets __hash__ = None. If Python allowed you to insert k = [1, 2] into a dictionary and you later ran k.append(3), its hash value would change—violating Rule #1 (Hash Stability) so subsequent lookups would probe the wrong table slots and fail to find the key.
Why isinstance(obj, Hashable) vs. hash(obj) Behaves Differently
Developers often try to test hashability before inserting into a dict or set, but the two checks answer different questions:
isinstance(obj, Hashable)(Shallow Type-Level Check): Only checks whethertype(obj).__hash__ is not None. Becausetuple.__hash__is defined,isinstance(([1, 2], "meta"), Hashable)returnsTrue—even though that tuple contains alistand will crash when hashed!hash(obj)insidetry / except TypeError(Practical Instance-Level Test): While not a static type classification (since container types liketupleandfrozensetare conditionally hashable depending on what they currently hold), callinghash(obj)is the practical runtime test that recursively verifies whether that specific object instance and all of its nested contents can be hashed right now:
from collections.abc import Hashable
def can_hash_instance(obj):
try:
hash(obj)
return True
except TypeError:
return False
nested = ([1, 2], "meta")
print("isinstance(nested, Hashable):", isinstance(nested, Hashable))
print("can_hash_instance(nested): ", can_hash_instance(nested))
print("Hash collision (-1 vs -2): ", hash(-1), "==", hash(-2), "| Slot in 8-slot table:", -2 & 7)Verified Output (Python 3.10.16):
isinstance(nested, Hashable): True can_hash_instance(nested): False Hash collision (-1 vs -2): -2 == -2 | Slot in 8-slot table: 6
Step-by-Step Debugging Workflow
When TypeError: unhashable type: 'list' appears in your traceback, follow this 6-step procedure to find the offending list:
- Identify the hashing operation on the failing line: Check the bottom line of your traceback for
{k: v},d[k],d.get(k),k in my_set,set(items),Counter(items),@lru_cache, or a Pandas deduplication/grouping method (drop_duplicates(),groupby(),unique()). - Identify the exact candidate key or element: If you are passing a sequence of items into
set(items)ordict(pairs), the error is notitemsitself—it is one of the elements insideitems. - Test elements with
hash(item)in a loop: If only one record in a 10,000-row dataset is crashingset()or Pandas, run a quick loop withtry: hash(x)/except TypeError:to print the exact index andrepr(x)of the unhashable element. - Inspect nested tuples for hidden lists: If
type(x)istuple, inspect[type(el).__name__ for el in x]—a singlelistnested inside atupletriggers the exact sameTypeError: unhashable type: 'list'message. - Decide whether to convert or restructure: Check the decision guide below to see whether you should convert the
listto atuple/frozenset, key by a unique scalar ID instead, or fix an accidental{...}set literal.
Common Causes of TypeError: unhashable type: 'list'
Here are the seven most frequent ways a list (or a sibling mutable type) triggers an unhashable TypeError.
1. Using a list as a Dictionary Key (Or Passing a list to dict.get() / in)
Whether you are assigning a key (d[[1, 2]] = "val"), building a dict literal ({[1, 2]: "val"}), or merely checking if a key exists ([1, 2] in d or d.get([1, 2])), Python must hash the key first. Even if the dictionary is completely empty ({}.get([1, 2])), passing a list to .get() or in immediately raises TypeError: unhashable type: 'list'.
- The Trigger (Verified 3.10.16):
cache = {}
key = ["user", 1042]
cache[key] = "active"
# TypeError: unhashable type: 'list'- The Fix: Convert the list key into a
tuple(("user", 1042)ortuple(key)) or format it into a delimiter-separated string (f"{key[0]}:{key[1]}"):
cache = {}
key = ("user", 1042)
cache[key] = "active"
print(cache.get(("user", 1042))) # Prints: active2. Deduplicating a 2D List of Lists with set() or collections.Counter()
While set([1, 2, 1]) works because the elements inside the list are integers, calling set([[1, 2], [3, 4], [1, 2]]) (or Counter(rows)) tries to add each inner [1, 2] list as a member of the set—crashing on index 0!
Similarly, testing membership with [1, 2] in valid_set crashes because set.__contains__ hashes the left operand [1, 2], whereas [1, 2] in valid_list succeeds because list.__contains__ performs a linear equality scan without hashing.
- The Trigger (Verified 3.10.16):
rows = [[1, 2], [3, 4], [1, 2]] unique_rows = set(rows) # TypeError: unhashable type: 'list'
- The Fix (Flat Inner Lists): Convert each flat inner list to a
tupleusing a generator expression (tuple(r) for r in rows). Usedict.fromkeys()instead ofset()so the original row order is preserved:
rows = [[1, 2], [3, 4], [1, 2]] unique_rows = [list(t) for t in dict.fromkeys(tuple(r) for r in rows)] print(unique_rows) # [[1, 2], [3, 4]]
3. The Nested Tuple Trap: A tuple Containing a list or dict (([1, 2], "meta"))
A tuple is only hashable if every single element inside it is also hashable. When hash(my_tuple) runs, CPython recursively calls hash() on each item inside the tuple. If element 0 of your tuple is a list (([1, 2], "meta")), Python raises TypeError: unhashable type: 'list'—even though the outer container is already a tuple!
- The Trigger (Verified 3.10.16):
bad_tuple = ([1, 2], "meta")
seen = {bad_tuple}
# TypeError: unhashable type: 'list'- The Fix (Recursive
freeze_data()with Leaf Hashability Verification): When freezing deeply nested structures, a production helper must handle four details:
- Recurse into both
listandtuple: If atupleis at the top level (([1, 2], "meta")), checking onlyisinstance(obj, list)would return the outertupleuntouched with the mutableliststill inside. - Avoid
sorted(d.items())on arbitrary dicts: Dictionaries with mixed, non-comparable keys ({1: "a", "b": 2}) crashsorted()withTypeError: '<' not supported between instances of 'str' and 'int'. - Freeze both dict keys and values into a
frozenset:frozenset((freeze_data(k), freeze_data(v)) for k, v in obj.items())is order-independent and recursively freezes nested values. - Convert
bytearrayand verify scalar leaves withhash(obj): Convertbytearraytobytes, and callhash(obj)on any leaf object in the base case so custom unhashable leaf objects fail immediately insidefreeze_data()with a clear traceback:
def freeze_data(obj):
if isinstance(obj, (list, tuple)):
return tuple(freeze_data(x) for x in obj)
if isinstance(obj, dict):
return frozenset((freeze_data(k), freeze_data(v)) for k, v in obj.items())
if isinstance(obj, (set, frozenset)):
return frozenset(freeze_data(x) for x in obj)
if isinstance(obj, bytearray):
return bytes(obj)
# Validate that leaf / scalar object is genuinely hashable:
hash(obj)
return obj
bad_tuple = ([1, 2], {"role": ["admin", bytearray(b"raw")], 10: "ten"})
seen = {freeze_data(bad_tuple)}
print("Successfully hashed nested structure! Count:", len(seen))
# Verified Output: Successfully hashed nested structure! Count: 1Can You Fix This Nested Tuple Set Error?
record = ("user_101", ["read", "write"]) seen = {record} print(seen)
Why did {record} raise TypeError: unhashable type: 'list' when record is already a tuple, and how do you fix it?
4. Passing a list Argument to @functools.lru_cache or @functools.cache
Decorators like @functools.lru_cache and @functools.cache memoize function results by storing (args, kwargs) as keys in an internal dictionary. If you pass a list argument into a cached function (sum_scores([10, 20, 30])), lru_cache attempts to hash the argument tuple ([10, 20, 30],) and immediately crashes with TypeError: unhashable type: 'list'.
- The Trigger (Verified 3.10.16):
from functools import lru_cache
@lru_cache(maxsize=128)
def sum_scores(scores):
return sum(scores)
print(sum_scores([10, 20, 30]))
# TypeError: unhashable type: 'list'- The Fix (Direct Tuple Conversion vs. Public Wrapper Pattern):
- Option A: Pass a
tupleat the call site (sum_scores(tuple(scores))). - Option B (Practical Alternative When Callers Pass Lists): If you don’t want to force every caller in your codebase to cast lists to tuples before calling your function, keep a public wrapper function that accepts any
Iterable[int](including alist), converts it to atupleinternally, and delegates to the private@lru_cachehelper:
from collections.abc import Iterable
from functools import lru_cache
@lru_cache(maxsize=128)
def _sum_scores_cached(scores: tuple[int, ...]) -> int:
return sum(scores)
def sum_scores(scores: Iterable[int]) -> int:
# Callers can pass a list [10, 20, 30] without worrying about lru_cache!
return _sum_scores_cached(tuple(scores))
print(sum_scores([10, 20, 30])) # Prints: 605. Slicing a Dictionary (my_dict[0:2] — Python < 3.12 vs. Python 3.12+)
When you accidentally write slice syntax users[0:2] on a dict thinking it is a list, Python creates a slice(0, 2, None) object and passes it to dict.__getitem__() as a dictionary key! What happens next depends on your Python version:
- In Python 3.11 and earlier (Verified 3.10.16):
sliceobjects are not hashable (slice.__hash__isNone), sousers[0:2]raisesTypeError: unhashable type: 'slice'. - In Python 3.12+ (not run by me; noted from documentation): Python 3.12 made
sliceobjects hashable! Becauseslice(0, 2, None)can now be hashed,users[0:2]searches the dictionary for the literal keyslice(0, 2, None)and raisesKeyError: slice(0, 2, None)instead. - The Trigger (Verified 3.10.16):
users = {0: "Alice", 1: "Bob", 2: "Charlie"}
first_two = users[0:2]
# Python <= 3.11: TypeError: unhashable type: 'slice'
# Python >= 3.12: KeyError: slice(0, 2, None)The Fix (All Python Versions): Use itertools.islice() or convert .items() to a list before slicing:
from itertools import islice
users = {0: "Alice", 1: "Bob", 2: "Charlie"}
first_two = dict(islice(users.items(), 2))
print(first_two) # {0: 'Alice', 1: 'Bob'}6. Pandas .drop_duplicates(), .groupby(), .unique(), and .merge() on List Columns
In Pandas 2.0.0, methods that deduplicate, group, or join rows using a Cython hash table (PyObjectHashTable) fail whenever an object-dtype column contains Python list objects.
Here is the exact verified behavior across common Pandas 2.0.0 operations when df["tags"] contains lists ([["py", "seo"], ["js"], ["py", "seo"]]):
df.drop_duplicates()&df.duplicated(): RaisesTypeError: unhashable type: 'list'.df.groupby("tags").size(): RaisesTypeError: unhashable type: 'list'.df["tags"].unique(): RaisesTypeError: unhashable type: 'list'.df.value_counts()(DataFrame-level) &pd.merge(df, df, on="tags"): RaisesTypeError: unhashable type: 'list'.df["tags"].value_counts()(Series-level): Succeeds in Pandas 2.0.0 because Seriesvalue_counts()catches the hashTypeErrorinternally and falls back to a non-hash path, even though DataFramedf.value_counts()fails.- The Trigger (Verified Pandas 2.0.0):
import pandas as pd
df = pd.DataFrame({"id": [1, 2, 1], "tags": [["py", "seo"], ["js"], ["py", "seo"]]})
clean_df = df.drop_duplicates()
# TypeError: unhashable type: 'list'The Fix (Flat 1D Lists vs. Nested Lists/Dicts):
- Option 1 (Ignore list columns): Pass
subset=["id"]to.drop_duplicates()so Pandas only hashes scalar columns. - Option 2 (For flat 1D lists of scalars): Convert each list cell to a tuple with
.map(lambda x: tuple(x) if isinstance(x, list) else x). - Option 3 (For nested lists or dicts inside cells): Because
.map(tuple)is shallow (it turns[[1, 2], [3, 4]]into([1, 2], [3, 4]), which still contains inner lists and crashes!), apply the recursivefreeze_datafunction from Cause #3 (df["matrix"].map(freeze_data)) whenever cells hold nested structures:
import pandas as pd
df = pd.DataFrame({"id": [1, 2, 1], "tags": [["py", "seo"], ["js"], ["py", "seo"]]})
# Option 1: Deduplicate using only hashable scalar columns
clean_df = df.drop_duplicates(subset=["id"])
# Option 2 (Flat 1D list column): Shallow conversion to tuple
df_flat = df.assign(tags=df["tags"].map(lambda x: tuple(x) if isinstance(x, list) else x)).drop_duplicates()
# Option 3 (Nested list/dict column): Recursive conversion with freeze_data
df_nested = pd.DataFrame({"id": [1, 1], "matrix": [[[1, 2], [3, 4]], [[1, 2], [3, 4]]]})
clean_nested = df_nested.assign(matrix=df_nested["matrix"].map(freeze_data)).drop_duplicates()
print("Nested deduplicated rows:", len(clean_nested)) # Prints: 17. Custom Classes Overriding __eq__ & @dataclass Parameters
In Python, a regular user-defined class inherits object.__hash__() and hashes by its memory address (id(self)). However, if a regular class defines __eq__() without also defining __hash__(), Python automatically sets __hash__ = None, making instances unhashable.
For @dataclass, whether Python generates a __hash__() method depends on the decorator parameters (eq, frozen, and unsafe_hash):
@dataclass(defaulteq=True, frozen=False): Sets__hash__ = None. Instances are unhashable (TypeError: unhashable type: 'Point').@dataclass(frozen=True)(with defaulteq=True): Generates a value-based__hash__()method. Instances are hashable (provided all field values inside the dataclass are also hashable!).@dataclass(eq=False): Does not generate__eq__(), so the class inheritsobject.__hash__()and hashes by object identity (id).@dataclass(unsafe_hash=True): Forces@dataclassto generate a value-based__hash__()even whenfrozen=False. (⚠️ Avoid mutating fields after putting anunsafe_hash=Trueinstance into adictorset, or you will violate the hashability contract!)- The Trigger & Fix (Verified 3.10.16):
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
tags: tuple[str, ...] = () # Use tuple, not list, for collection fields!
pts = {Point(1, 2, ("start",))}
print(pts) # {Point(x=1, y=2, tags=('start',))}When NOT to Convert a list to a tuple (And What to Do Instead)
Blindly wrapping every list in tuple(...) is sometimes a band-aid over the wrong data structure. Here are four situations where you should not convert a list to a tuple:
- The List Is a Full Record That Already Has a Unique ID (
[1042, "Alice", ["admin"]]): If you are storing user or order records in a dictionary, don’t use the entire record as the dictionary key! Use the scalar unique ID (record[0]orrecord["id"]) as the key, and keep the mutable record as the dictionary value (users_by_id[record[0]] = record). Dictionary values can be mutated freely and never need to be hashable. - Element Order Does Not Matter (
["read", "write"]vs.["write", "read"]): In atuple, order matters:("read", "write") != ("write", "read"), so they hash to two separate keys. If your list represents an unordered set of tags or permissions where order should be ignored, convert it to afrozenset(frozenset(perms)) instead of atuple. - You Still Need to Append or Mutate the Collection In-Place: Tuples cannot be mutated. If you need to
.append()items as you group data, usecollections.defaultdict(list)where the key is an immutable scalar/tuple and the value is the mutablelist. - You Accidentally Used Set Braces
{...}Instead of List Brackets[...]: Writingmatrix = {[1, 2], [3, 4]}creates asetliteral and crashes immediately. If you just wanted a 2D list of lists, change the outer curly braces to square brackets:matrix = [[1, 2], [3, 4]].
Decision Table: Choosing the Right Fix for Your Data Structure
| What Your list Represents | Best Fix / Data Structure | Why This Is the Right Choice |
Ordered coordinates, path, or composite key ([x, y], ["us", "ny"]) | tuple(my_list) | Order matters ((10, 20) != (20, 10)) and length/order is fixed once created. |
Unordered set of tags, roles, or IDs (["admin", "editor"]) | frozenset(my_list) | Order-independent and deduplicated (frozenset(["a", "b"]) == frozenset(["b", "a"])). |
Entity record with a primary key ({"id": 101, "tags": ["a"]}) | Key by scalar ID (d[row["id"]] = row) | Avoids hashing nested mutable fields; keeps the record mutable as the dict value. |
Named domain record used in sets (Point, UserKey) | @dataclass(frozen=True) or NamedTuple | Gives readable .x / .id attribute access while remaining immutable and hashable. |
Collection you need to .append() to inside a dict | defaultdict(list) (d[key].append(val)) | Keeps the dict key hashable while storing the growing list as the dict value. |
Mutable vs. Immutable Counterparts (Including Dict & NumPy Caveats)
When you do need an immutable, hashable version of a mutable container, use this reference table—and pay close attention to the caveats for dictionaries and NumPy arrays:
| Mutable Type (Unhashable) | Immutable Counterpart (Hashable) | Safe Conversion Pattern | Important Caveats (Nested & Multi-D Traps) |
list | tuple | Flat 1D: tuple(my_list)Nested: freeze_data(my_list) | tuple(my_list) is shallow—if my_list contains inner lists ([[1, 2]]), you must convert inner lists recursively! |
set | frozenset | frozenset(my_set) | Unordered; all elements inside must already be hashable. |
dict | frozenset of (k, v) pairs | Flat: frozenset(d.items())Nested: freeze_data(d) | ⚠️ tuple(sorted(d.items())) has two traps:1. Mixed keys ( {1: "a", "b": 2}) crash sorted() with TypeError: '<' not supported.2. Nested list/dict values remain unhashable unless frozen recursively with freeze_data(d). |
numpy.ndarray | tuple or (shape, dtype, bytes) | 1D: tuple(arr.tolist())2D: tuple(map(tuple, arr.tolist()))Numeric N-D: (arr.shape, arr.dtype.str, arr.tobytes())Object N-D: freeze_data(arr.tolist()) | ⚠️ (arr.shape, arr.dtype.str, arr.tobytes()) is only for fixed-width numeric/primitive (non-object) arrays. On dtype=object arrays, arr.tobytes() serializes raw PyObject* memory pointers rather than values—so two equal object arrays have different bytes! Use freeze_data(arr.tolist()) for object arrays (and normalize -0.0 / NaN if hashing floats by bytes). |
bytearray | bytes | bytes(my_bytearray) | Direct, exact immutable binary counterpart. |
Sibling unhashable type Error Variants
Python raises the exact same TypeError: unhashable type: '...' message for every other mutable container or series object (all verified on Python 3.10.16, NumPy 1.26.3, and Pandas 2.0.0):
| Error Message Variant (Verified 3.10.16) | What Triggered It | The Fix |
TypeError: unhashable type: 'dict' | Putting a dict inside a set (set([{"id": 1}, {"id": 2}])) or using {{...}} double braces around a dict literal. | For flat dicts with hashable values: frozenset(d.items()). For nested JSON dicts containing lists/dicts or mixed keys: use recursive freeze_data(d). |
TypeError: unhashable type: 'set' | Nesting a set inside another set ({{1, 2}, {3, 4}}) or using a set as a dict key. | Convert inner sets to frozenset: {frozenset({1, 2}), frozenset({3, 4})}. |
TypeError: unhashable type: 'slice' (Python <= 3.11; KeyError in 3.12+) | Slicing a dictionary (my_dict[0:5]) or indexing a dictionary with a comma/colon (my_dict[:, 0]). | Slice list(my_dict.items())[0:5], or use dict(islice(my_dict.items(), 5)). |
TypeError: unhashable type: 'bytearray' | Using a mutable bytearray buffer as a dict key or set element. | Convert to immutable bytes first: bytes(buf). |
TypeError: unhashable type: 'numpy.ndarray' (NumPy 1.26.3) | Using a NumPy array as a dict key or passing a 2D array directly to set(arr). | Use np.unique(arr, axis=0) to deduplicate rows, freeze_data(arr.tolist()) for nested/object arrays, or (arr.shape, arr.dtype.str, arr.tobytes()) for numeric N-D keys. |
TypeError: unhashable type: 'Series' (Pandas 2.0.0) | Passing a Pandas Series (df["col"]) as a dictionary key (my_dict[df["col"]]) instead of using .map(my_dict). | To map a Series through a dictionary, call df["col"].map(my_dict). |
Catch Unhashable Keys Before Runtime with Type Checkers and Linters
Static analysis tools and type checkers detect unhashable dictionary keys and set elements in your IDE before you run the script (not run by me; representative diagnostics noted from documentation—exact wording and error codes vary by tool version and configuration):
coords: list[int] = [10, 20]
seen: set[tuple[int, ...]] = {coords} # <-- Flagged in IDE before runtime!Pylint (
E1143unhashable-member): Specifically checks dictionary keys and set literals for unhashable types likelist,dict, andset(e.g.,E1143: Value 'coords' is unhashable/unhashable-member).Mypy & Pyright / Pylance: When you annotate collection parameters with
from collections.abc import Hashableor specific immutable types (dict[tuple[int, int], str]), both Mypy and Pyright immediately flag passing alist[int]where atuple[int, int]orHashableis required.
Worked Examples: 2D List Deduplication & Pandas List Columns
Let’s walk through two complete production scenarios where TypeError: unhashable type: 'list' occurs and how to solve both cleanly.
Worked Example 1: Deduplicating JSON Coordinate Pairs While Preserving Order
Suppose your backend receives a JSON array of [lat, lon] GPS coordinate pairs ([[40.71, -74.00], [34.05, -118.24], [40.71, -74.00]]) and tries to remove duplicate coordinates using list(set(pings)).
The Crashing Code (/var/www/app/main.py):
def get_unique_locations(pings):
return list(set(pings))
raw_pings = [[40.71, -74.00], [34.05, -118.24], [40.71, -74.00]]
print(get_unique_locations(raw_pings))Verified Traceback (Python 3.10.16):
Traceback (most recent call last):
File "/var/www/app/main.py", line 5, in <module>
print(get_unique_locations(raw_pings))
File "/var/www/app/main.py", line 2, in get_unique_locations
return list(set(pings))
TypeError: unhashable type: 'list'The Thought Process & Fix:
- Because JSON only has arrays (
[...]),json.loads()parses every[lat, lon]pair as a mutable Pythonlist. - Passing
pingsintoset(pings)attempts to hash[40.71, -74.00], which fails immediately withTypeError: unhashable type: 'list'. - Furthermore, even if
set()worked, sets are unordered and would scramble the chronological order of the GPS pings! - The Production Fix (Verified 3.10.16): Convert each flat inner list to a
tupleand deduplicate withdict.fromkeys()(or aseenset) to preserve the exact arrival order:
# Approach A (Returns list of (lat, lon) tuples — cleanest Python representation):
def get_unique_locations_tuples(pings):
return list(dict.fromkeys(tuple(coord) for coord in pings))
# Approach B (Returns list of [lat, lon] lists — if downstream JSON serializers require lists):
def get_unique_locations_lists(pings):
seen = set()
unique = []
for coord in pings:
key = tuple(coord)
if key not in seen:
seen.add(key)
unique.append(coord)
return unique
raw_pings = [[40.71, -74.00], [34.05, -118.24], [40.71, -74.00]]
print("As tuples:", get_unique_locations_tuples(raw_pings))
print("As lists: ", get_unique_locations_lists(raw_pings))
# Verified Output:
# As tuples: [(40.71, -74.0), (34.05, -118.24)]
# As lists: [[40.71, -74.0], [34.05, -118.24]]Worked Example 2: Deduplicating a Pandas DataFrame with Flat or Nested List Columns
When you load JSON into a Pandas DataFrame, array fields like "items" are stored as Python list objects inside an object-dtype column. Calling df.drop_duplicates() across all columns crashes in Pandas’ Cython hash table.
The Production Fix (Verified Pandas 2.0.0):
- Use
subset=["order_id"]if you only need to deduplicate by scalar key columns. - Use
.map(lambda x: tuple(x) if isinstance(x, list) else x)when the column contains flat 1D lists of scalars (["kbd", "mouse"]). - Use
.map(freeze_data)(from Cause #3) if the column contains nested lists or dicts ([{"sku": "kbd"}]).
import pandas as pd
df = pd.DataFrame({
"order_id": [101, 102, 101],
"items": [["kbd", "mouse"], ["monitor"], ["kbd", "mouse"]],
})
# Strategy 1 (Fastest): Deduplicate using only the scalar primary-key column(s)
dedup_by_id = df.drop_duplicates(subset=["order_id"])
# Strategy 2 (Full-row deduplication for flat 1D lists): Convert list cells to tuples
dedup_all = df.assign(
items=df["items"].map(lambda x: tuple(x) if isinstance(x, list) else x)
).drop_duplicates()
print("By subset:", dedup_by_id.to_dict(orient="records"))
print("By tuple: ", dedup_all.to_dict(orient="records"))
# Verified Output:
# By subset: [{'order_id': 101, 'items': ['kbd', 'mouse']}, {'order_id': 102, 'items': ['monitor']}]
# By tuple: [{'order_id': 101, 'items': ('kbd', 'mouse')}, {'order_id': 102, 'items': ('monitor',)}]Can You Fix This Pandas drop_duplicates() Crash?
df = pd.DataFrame({"id": [1, 1], "tags": [["a", "b"], ["a", "b"]]}) clean_df = df.drop_duplicates() print(clean_df)
Choose the best fix to deduplicate this flat list column across all rows:
Frequently Asked Questions
Dictionary keys and set elements are stored in hash table slots derived from hash(key). If Python allowed mutable lists as keys and you modified a list after inserting it into a dictionary, its hash value would change and subsequent lookups would probe the wrong table slots. Because a tuple cannot be modified in place after creation, its hash value is guaranteed to stay constant (provided every item inside the tuple is also hashable).
TypeError: unhashable type: 'list'?A tuple computes its hash by recursively calling hash() on each element inside it. If your tuple contains a list, dict, or set at any nesting level—such as ("user_1", ["admin", "editor"])—hashing the tuple fails as soon as Python reaches the inner list. Convert the inner list to a tuple as well: ("user_1", ("admin", "editor")).
[1, 2] in my_set raise a TypeError, while [1, 2] in my_list returns False?When the right side of in is a list ([1, 2] in [(1, 2), (3, 4)]), Python scans the list sequentially and compares items using ==, which does not require hashing. When the right side of in is a set or dict, Python immediately calls hash([1, 2]) to compute the hash table slot, triggering TypeError: unhashable type: 'list'.
TypeError: unhashable type: 'slice' (and why does Python 3.12+ raise KeyError instead)?You wrote slice syntax like my_dict[0:5] (or my_dict[:, 0]) on a Python dictionary. In Python, 0:5 inside square brackets creates a slice(0, 5, None) object and passes it to my_dict.__getitem__() as a key lookup. In Python 3.11 and earlier, slice objects are unhashable and raise TypeError: unhashable type: 'slice'. In Python 3.12+, slice objects became hashable, so Python searches the dictionary for that slice key and raises KeyError: slice(0, 5, None). In all versions, slice list(my_dict.items())[:5] or use itertools.islice(my_dict.items(), 5).
@dataclass hashable so I can put it in a set or dict?Decorate the class with @dataclass(frozen=True) and ensure all of its fields use immutable types (such as tuple[str, ...] instead of list[str]). By default, @dataclass sets eq=True, frozen=False, which sets __hash__ = None; adding frozen=True prevents attribute mutation and instructs Python to generate a value-based __hash__() method automatically.
Official Documentation & Related Fixes
- Master Guide: The Ultimate Python Debugging Guide: Tracebacks, Exceptions, and Fixes
- Related Error: How to Fix TypeError: list indices must be integers or slices, not str
- Related Error: How to Fix KeyError in Python (Dictionaries, JSON & Pandas)
- Related Error: How to Fix AttributeError: ‘list’ object has no attribute ‘x’
- Official Python Docs: Glossary — hashable

