Python 3 reference · Built-in Functions
Python hash() Function
Return the hash value of an object: an integer used by dicts and sets to find keys quickly. Only immutable values are hashable.
Python 3 Since 3.0
Syntax
hash(object)
Parameters
| Parameter | Description |
|---|---|
object |
A hashable object (numbers, strings, tuples of hashables, frozensets, …). |
Return value
An int.
Examples
print(hash(42), hash(True), hash(1.0) == hash(1))
print(hash((1, 2)) == hash((1, 2)))
Output
42 1 True True
try:
hash([1, 2])
except TypeError as e:
print("TypeError:", e)
print(hash(tuple([1, 2])) == hash((1, 2)))
Output
TypeError: unhashable type: 'list' True
Good to know
- String and bytes hashes are randomised per process for security, so don't store them or rely on them
across runs. Use
hashlibfor stable checksums. - If you define
__eq__()on a class, also define__hash__()(or set it toNone) so equal objects hash equally.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
id()· Return an object's identity: a unique integer for the object while it exists. In CPython it is the memory address.frozenset()· Create an immutable set: unique items that can't be added or removed, so it is hashable and can be a dict key.frozendict()· Create an immutable, hashable dictionary (new in Python 3.15). It can be a dict key or set member and can't be changed.tuple()· Create a tuple: an ordered, immutable sequence. Tuples are hashable when their items are, so they can be dict keys.- Python Dictionaries · tutorial