Python hash() 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
- Parameter object:
- Type: any object
- Description: the object whose hash value is computed.
Function description
- Return Value: returns the object's hash value (an integer).
- Requirement: the object must be hashable (i.e. it implements the __hash__ method).
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
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
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 function