liveBook · Manning

Unhashable

As explained in Python Workout: 50 ten-minute exercises

Unhashable describes a Python object whose value cannot be used as a dictionary key or set element because it lacks a suitable stable hash value.

An unhashable object cannot serve as a dictionary key or set element because its value cannot provide a stable hash. Mutable built-in types such as lists are unhashable: changing the object could change its hash, leaving a stored key impossible to find. section 4.1

A list cannot be a dictionary key

```python key = ["red", "green"] # A list is mutable, so it cannot safely be used as a key. data = {key: "colors"} ``` A dictionary must be able to find a key after insertion. If the list changed, its hash could change too, so Python prevents this use rather than allowing an unreachable key-value pair. section 4.1

Keep these distinctions in mind:

  • Hashable and immutable are not identical terms, although they overlap substantially. section 4.1
  • Hashing supports fast dictionary-key lookup and key uniqueness; it does not provide value lookup. section 4.1

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains mutation, changing hashes, and unreachable key-value pairs while deferring finer distinctions between hashability and immutability.
Examples
Uses mutable lists as dictionary keys to demonstrate why changing a key could make its stored value unfindable.
What it assumes
Assumes familiarity with Python dictionaries, sets, mutability, and basic key-value lookup.
What you can do after
Diagnose why a mutable object cannot be used as a dictionary key or set element.
How it connects
Connects unhashable objects with dictionaries, sets, hash functions, mutable types, and immutable objects.

Also explained in

Compare how 2 books explain unhashable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.