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

ParameterDescription
object A hashable object (numbers, strings, tuples of hashables, frozensets, …).

Return value

An int.

Examples

Equal values have equal hashesTry it yourself
print(hash(42), hash(True), hash(1.0) == hash(1))
print(hash((1, 2)) == hash((1, 2)))

Output

42 1 True
True
Lists aren't hashableTry it yourself
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 hashlib for stable checksums.
  • If you define __eq__() on a class, also define __hash__() (or set it to None) so equal objects hash equally.

Version history

VersionChange
Python 3.0Added