Python hash() Function

Python3 内置函数Python3 Built-in Functions


hash()is a built-in function in Python used to return the hash value of an object.

The hash value is an integer used for quickly comparing objects. Dictionary keys and set elements are required to be hashable. Immutable objects are usually hashable.

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


Basic Syntax and Parameters

Syntax Format

hash(object)

Parameter Description

  • Parameter object:
    • Type: Any object
    • Description: The object whose hash value is to be computed.

Function Description

  • Return Value: Returns the hash value (integer) of the object.
  • Requirement: The object must be hashable (i.e., it implements the __hash__ method).

Examples

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: hash value
print(hash("world"))   # Output: another hash value

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

# List (not hashable)
# print(hash([1, 2, 3])) # will raise 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: hash value

Output:

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

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


Python3 内置函数Python3 Built-in Functions


Other Extensions