Python Reference ยท Built-in Functions
Python hash() function
Reference for Python hash(): the integer hash of hashable objects, why strings change between runs, the equality contract and why lists cannot be dictionary keys.
hash(obj) returns an integer called the hash value of the object. Dictionaries and sets use it to find items quickly: they compute the hash of a key, jump to a bucket, and then compare with ==.
Only hashable objects have a hash. Immutable built-ins such as numbers, strings, tuples of hashable items and frozensets are hashable; lists, dictionaries and sets are not. The values are an implementation detail, so never store them or rely on specific numbers.
print(hash(42)) # 42
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
hash(object)
| Name | Description |
|---|---|
object |
Any hashable object. |
Return value: an int. It calls the object's __hash__() and truncates the result to the platform's Py_ssize_t size if necessary.
Raises: TypeError ("unhashable type") if the object does not support hashing.
Usage notes
- The contract: objects that compare equal must have equal hashes. The reverse is not required; different objects may collide.
- Numbers hash by value.
hash(1) == hash(1.0) == hash(True), consistent with1 == 1.0 == True. - String hashes are randomized per process (unless
PYTHONHASHSEEDis fixed), to resist denial-of-service attacks on dictionaries. Never persist them or use them as stable identifiers; usehashlibfor that. - Integers hash to themselves for small values, except that
-1hashes to-2because-1is reserved as an error marker in the C API. - Mutability and hashing don't mix. If an object's hash depends on data that can change, it will be lost inside dictionaries and sets. That is why lists are unhashable.
- Defining
__eq__sets__hash__toNoneunless you define both. Dataclasses withfrozen=True(orunsafe_hash=True) generate__hash__for you. - Tuples are hashable only if all elements are, so
hash((1, [2]))fails. - Not a cryptographic hash. For checksums and passwords use
hashlib,hmacorsecrets.
Related
__eq__()and__hash__(),frozenset(),id(),set(),dict()- Lessons: Dictionaries, Special methods