Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python hash() Function

Python hash() Function

Python3 Built-in Functions Python3 built-in function


hash() is a built-in Python function that returns an object's hash value.

A hash value is an integer used to compare objects quickly. Dictionary keys and set elements must both be hashable. Immutable objects are usually hashable.

Word meaning: hash 意为"哈希",返回对象的哈希值。


Basic syntax and parameters

Syntax format

hash(object)

Parameter Description

Function description


Example

Example 1: basic usage

Example

# Numbers
print(hash(1))        # Output: 1
print(hash(3.14))     # Output: 314159
print(hash(-100))     # Output: -100

# Strings
print(hash("hello"))   # Output: a hash value
print(hash("world"))   # Output: another hash value

# Tuple (hashable)
print(hash((1, 2, 3)))  # Output: a hash value

# List (not hashable)
# print(hash([1, 2, 3])) # raises TypeError

Expected output:

Objects with the same value always have the same hash value.

Example 2: use in dictionaries and sets

Example

# Dictionary keys must be hashable
d = {"name": "Tom", "age": 20}
print(d["name"])  # Output: Tom

# Set elements must be hashable
s = {1, 2, 3, "hello"}
print(3 in s)     # Output: True

# Hash of a custom class
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __hash__(self):
        return hash((self.x, self.y))

p = Point(1, 2)
print(hash(p))  # Output: a hash value

Result:

Hash values allow objects to be used as dictionary keys and set elements.

hash() is the foundation of hash-related operations in Python.


Python3 Built-in Functions Python3 built-in function