Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Python · Function

hash

hash() returns an integer hash value for an object that provides one. Python uses hashes to speed dictionary-key lookup, and equal numeric values share the same hash even across types.

How it works

hash() returns an integer hash value for an object when that object provides one. Python uses these values to compare dictionary keys efficiently; custom hash implementations are constrained by the host machine's integer width.

Syntax

hash(object, /)

Parameters

NameTypeDescription
objectobjectThe object whose hash value should be returned; it must provide a hash value.

Returns

An integer hash value, if the object has one.

Key points

  • The function accepts an object and returns its hash value when one exists.
  • The result is an integer.
  • Dictionary lookup uses hashes to compare keys quickly.
  • Equal numeric values must have identical hashes.
  • Different numeric types can share a hash when their values compare equal.

Common mistakes

  • A custom __hash__() result can be truncated according to the host machine's bit width.

Example: Hash a tuple

key = ("user", 42)
print(hash(key))

Computes the integer hash for a tuple, which is suitable for use as a dictionary key.

When to use it

Inspect hashability

Checking whether a value exposes hashing behavior before using it as a dictionary key.

Work with custom hashes

Implementing or reviewing custom classes that define __hash__().

Analyze numeric keys

Understanding dictionary behavior for numerically equal keys such as 1 and 1.0.

Interview questions

QWhat does hash() return and why is it useful?

hash() returns an integer for an object that has a hash value. Dictionary lookup uses hash values to compare keys quickly.

Follow-up: What equality rule should numeric keys follow? Values that compare equal must produce the same hash, even when their types differ.

QWhat happens when an object has no hash value?

Objects without a hash value cannot be passed successfully to hash(). Hashable values can participate in dictionary-key lookup.

Follow-up: Why might a mutable object be unsuitable as a key? Mutating key-relevant state can invalidate the hash-based lookup assumptions.

QHow does hash() treat equal numeric values of different types?

Equal numeric values share a hash, so 1 and 1.0 produce the same hash even though they have different types. This preserves consistent dictionary-key behavior.

Follow-up: What implementation detail affects custom hash results? Python truncates custom __hash__() results to the host machine's bit width.

  • __hash__()
  • dict
  • dictionary keys

Source: Built-in functions. Checked 2026-10-16.