Skip to content
Tutorials Center
My learning

Topics

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.

Python
print(hash(42))
# 42

Try it

Python What is hashable

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.

Python Your own hashable class

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

Python
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 with 1 == 1.0 == True.
  • String hashes are randomized per process (unless PYTHONHASHSEED is fixed), to resist denial-of-service attacks on dictionaries. Never persist them or use them as stable identifiers; use hashlib for that.
  • Integers hash to themselves for small values, except that -1 hashes to -2 because -1 is 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__ to None unless you define both. Dataclasses with frozen=True (or unsafe_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, hmac or secrets.