How to Fix TypeError: unhashable type: ‘list’ in Python

3D vector illustration for fixing unhashable type list error in Python sets and dict keys.

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: Player

2. 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 LikeRoot CauseThe 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

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:

  1. Hash Stability (Immutability Over Lifetime): An object’s hash value (hash(a)) must never change during its lifetime.
  2. 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 whether type(obj).__hash__ is not None. Because tuple.__hash__ is defined, isinstance(([1, 2], "meta"), Hashable) returns True—even though that tuple contains a list and will crash when hashed!
  • hash(obj) inside try / except TypeError (Practical Instance-Level Test): While not a static type classification (since container types like tuple and frozenset are conditionally hashable depending on what they currently hold), calling hash(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:

  1. 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()).
  2. Identify the exact candidate key or element: If you are passing a sequence of items into set(items) or dict(pairs), the error is not items itself—it is one of the elements inside items.
  3. Test elements with hash(item) in a loop: If only one record in a 10,000-row dataset is crashing set() or Pandas, run a quick loop with try: hash(x) / except TypeError: to print the exact index and repr(x) of the unhashable element.
  4. Inspect nested tuples for hidden lists: If type(x) is tuple, inspect [type(el).__name__ for el in x]—a single list nested inside a tuple triggers the exact same TypeError: unhashable type: 'list' message.
  5. Decide whether to convert or restructure: Check the decision guide below to see whether you should convert the list to a tuple / 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) or tuple(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: active

2. 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 tuple using a generator expression (tuple(r) for r in rows). Use dict.fromkeys() instead of set() 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:
  1. Recurse into both list and tuple: If a tuple is at the top level (([1, 2], "meta")), checking only isinstance(obj, list) would return the outer tuple untouched with the mutable list still inside.
  2. Avoid sorted(d.items()) on arbitrary dicts: Dictionaries with mixed, non-comparable keys ({1: "a", "b": 2}) crash sorted() with TypeError: '<' not supported between instances of 'str' and 'int'.
  3. 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.
  4. Convert bytearray and verify scalar leaves with hash(obj): Convert bytearray to bytes, and call hash(obj) on any leaf object in the base case so custom unhashable leaf objects fail immediately inside freeze_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: 1

Can 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 tuple at 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 a list), converts it to a tuple internally, and delegates to the private @lru_cache helper:
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: 60

5. 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): slice objects are not hashable (slice.__hash__ is None), so users[0:2] raises TypeError: unhashable type: 'slice'.
  • In Python 3.12+ (not run by me; noted from documentation): Python 3.12 made slice objects hashable! Because slice(0, 2, None) can now be hashed, users[0:2] searches the dictionary for the literal key slice(0, 2, None) and raises KeyError: 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(): Raises TypeError: unhashable type: 'list'.
  • df.groupby("tags").size(): Raises TypeError: unhashable type: 'list'.
  • df["tags"].unique(): Raises TypeError: unhashable type: 'list'.
  • df.value_counts() (DataFrame-level) & pd.merge(df, df, on="tags"): Raises TypeError: unhashable type: 'list'.
  • df["tags"].value_counts() (Series-level): Succeeds in Pandas 2.0.0 because Series value_counts() catches the hash TypeError internally and falls back to a non-hash path, even though DataFrame df.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 recursive freeze_data function 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: 1

7. 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 (default eq=True, frozen=False): Sets __hash__ = None. Instances are unhashable (TypeError: unhashable type: 'Point').
  • @dataclass(frozen=True) (with default eq=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 inherits object.__hash__() and hashes by object identity (id).
  • @dataclass(unsafe_hash=True): Forces @dataclass to generate a value-based __hash__() even when frozen=False. (⚠️ Avoid mutating fields after putting an unsafe_hash=True instance into a dict or set, 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:

  1. 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] or record["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.
  2. Element Order Does Not Matter (["read", "write"] vs. ["write", "read"]): In a tuple, 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 a frozenset (frozenset(perms)) instead of a tuple.
  3. 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, use collections.defaultdict(list) where the key is an immutable scalar/tuple and the value is the mutable list.
  4. You Accidentally Used Set Braces {...} Instead of List Brackets [...]: Writing matrix = {[1, 2], [3, 4]} creates a set literal 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 RepresentsBest Fix / Data StructureWhy 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 NamedTupleGives readable .x / .id attribute access while remaining immutable and hashable.
Collection you need to .append() to inside a dictdefaultdict(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 PatternImportant Caveats (Nested & Multi-D Traps)
listtupleFlat 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!
setfrozensetfrozenset(my_set)Unordered; all elements inside must already be hashable.
dictfrozenset of (k, v) pairsFlat: 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.ndarraytuple 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).
bytearraybytesbytes(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 ItThe 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 (E1143 unhashable-member): Specifically checks dictionary keys and set literals for unhashable types like list, dict, and set (e.g., E1143: Value 'coords' is unhashable / unhashable-member).

    Mypy & Pyright / Pylance: When you annotate collection parameters with from collections.abc import Hashable or specific immutable types (dict[tuple[int, int], str]), both Mypy and Pyright immediately flag passing a list[int] where a tuple[int, int] or Hashable is 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:

  1. Because JSON only has arrays ([...]), json.loads() parses every [lat, lon] pair as a mutable Python list.
  2. Passing pings into set(pings) attempts to hash [40.71, -74.00], which fails immediately with TypeError: unhashable type: 'list'.
  3. Furthermore, even if set() worked, sets are unordered and would scramble the chronological order of the GPS pings!
  4. The Production Fix (Verified 3.10.16): Convert each flat inner list to a tuple and deduplicate with dict.fromkeys() (or a seen set) 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

Why are lists unhashable in Python while tuples are hashable?

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).

Why did my tuple still raise 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")).

Why does [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'.

What causes 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).

How do I make a @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.

Similar Posts

Leave a Reply