hash()

hash(object)
Returns: int · Added in v3.0 · Updated March 13, 2026 · Built-in Functions
hash object identity dictionary built-in

The hash() function returns the hash value of an object (if it has one). Hash values are integers that are used to quickly compare dictionary keys during a dictionary lookup. Two objects that compare equal must have the same hash value.

Syntax

hash(object)

Parameters

ParameterTypeDefaultDescription
objectobjectThe object to hash. Must be hashable (immutable).

Examples

Basic usage

# Hash of integers
print(hash(42))        # 42
print(hash(-42))       # -42

# Hash of strings
print(hash("hello"))  # 6720730533479563752 (may vary by Python version)

# Hash of tuples (tuples are hashable if their elements are hashable)
print(hash((1, 2, 3))) # 529344067295497451

Hash and dictionaries

# Dictionaries use hashes for fast lookups
d = {"key": "value"}
print(hash("key"))   # Hash of the string "key"
print(d["key"])       # "value"

Custom objects and hash

class Person:
    def __init__(self, name):
        self.name = name
    
    def __eq__(self, other):
        return self.name == other.name
    
    def __hash__(self):
        return hash(self.name)

p1 = Person("Alice")
p2 = Person("Alice")
print(hash(p1) == hash(p2))  # True (because they are equal)

Common Patterns

Using hash for membership testing

# Check if an object is hashable
def is_hashable(obj):
    try:
        hash(obj)
        return True
    except TypeError:
        return False

print(is_hashable("hello"))  # True
print(is_hashable([1, 2, 3])) # False (lists are not hashable)

Hash-based deduplication

# Deduplicate objects using hash
items = [{"a": 1}, {"a": 1}, {"b": 2}]
seen = set()
unique = []
for item in items:
    h = hash(tuple(sorted(item.items())))
    if h not in seen:
        seen.add(h)
        unique.append(item)
print(unique)  # [{"a": 1}, {"b": 2}]

Errors

TypeError: unhashable type

# Lists are mutable and not hashable
try:
    hash([1, 2, 3])
except TypeError as e:
    print(e)  # unhashable type: 'list'

This error occurs when you try to hash a mutable object (like a list, dict, or set) or an object that has explicitly set __hash__ to None.

See Also