hash()
The engine of dict and set lookups. Equal values give equal hashes; unhashable types raise.
Demo
hash() returns an integer hash. For SMALL INTEGERS, hash(n) == n — except hash(-1) which returns -2 (Python reserves -1 as an error sentinel internally). For floats, hash matches int for whole-number values. For BOOLEANS, hash(True) == 1 and hash(False) == 0. For STRINGS, Python randomizes the hash per process (PEP 456, hash randomization for security) — the values shown here are illustrative and will NOT match your Python REPL exactly. The property that MATTERS: equal values always hash equally within one process.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| object | Any | yes | A hashable value. Numbers, strings, tuples of hashables, frozensets — hashable. Lists, dicts, sets, and anything with mutable state — NOT hashable, raises TypeError. |
Return value
int — An integer hash for the object. Equal objects must have equal hashes. Mutable containers (list, dict, set) are unhashable and raise TypeError. For strings and bytes, the value is randomized per Python process (PEP 456) — same value within one run, different across runs.
Common patterns
lookup = {(x, y): compute(x, y) for x, y in coords}
def is_hashable(v): try: hash(v) return True except TypeError: return False
class Point: def __hash__(self): return hash((self.x, self.y)) def __eq__(self, other): return (self.x, self.y) == (other.x, other.y)
Examples
Pitfalls
hash([1, 2])
hash((1, 2))
hash("hello") # cache to disk?
import hashlib hashlib.sha256(b"hello").hexdigest()
hash(-1)
class C: def __eq__(self, o): return True hash(C())
class C: def __eq__(self, o): return True def __hash__(self): return 0
password_hash = hash(password)
import hashlib hashlib.sha256(pw.encode()).hexdigest()
When to use
- Almost never directly — hashing happens implicitly in dict / set
- Custom __hash__ on your own classes
- Testing whether an unknown value is hashable (with try/except)
- Occasional cache keys where the input is guaranteed hashable
- Cross-process consistency → hashlib is the right tool
- Security or password storage → hashlib.pbkdf2 / bcrypt / argon2
- Deterministic bucket assignment → hashlib with a fixed algorithm
- You want the raw value → id() gives object identity instead
Notes
FAQ
Because lists are mutable. If a list were a dict key, mutating it would invalidate the dict's lookup structure. Immutable containers (tuple, frozenset) are hashable and can serve as keys.