hash()
The built-in hash() function returns an integer hash value for a given object, which is used internally for fast lookups.
This hash value is used to quickly locate dictionary keys during lookups. Objects that compare equal must have the same hash value. Here’s how you can use the function:
>>> hash("Hello, world!")
-3907008302013813614
hash() Signature
hash(object)
Arguments
| Argument | Description |
|---|---|
object |
The object to be hashed. |
Return Value
- Returns an integer representing the hash value of the given object. The hash value is consistent within a single Python session but may vary between sessions for security reasons.
hash() Examples
With a string as an argument:
>>> hash("Real Python")
-456543210987654321
With a number as an argument:
>>> hash(42)
42
With a floating-point number as an argument:
>>> hash(3.14)
322818021289917443
hash() Common Use Cases
The most common use cases for the hash() function include:
- Creating hash values for dictionary keys
- Implementing hash tables
- Supporting custom objects in sets and dictionaries
hash() Real-World Example
Suppose you want to use custom objects as set members or dictionary keys. You can implement .__hash__() and .__eq__() to make your objects hashable:
class Employee:
def __init__(self, emp_id, name):
self.emp_id = emp_id
self.name = name
def __eq__(self, other):
return isinstance(other, Employee) and self.emp_id == other.emp_id
def __hash__(self):
return hash(self.emp_id)
def __repr__(self):
return f"Employee({self.emp_id}, '{self.name}')"
>>> team_a = {Employee(1, "Alice"), Employee(2, "Bob")}
>>> team_b = {Employee(2, "Bob"), Employee(3, "Charlie")}
>>> team_a & team_b
{Employee(2, 'Bob')}
By delegating to hash() on the emp_id attribute, two employees with the same ID are treated as the same person in sets and dictionaries, even if their names differ.
Related Resources
Tutorial
Build a Hash Table in Python With TDD
In this step-by-step tutorial, you'll implement the classic hash table data structure using Python. Along the way, you'll learn how to cope with various challenges such as hash code collisions while practicing test-driven development (TDD).
For additional information on related topics, take a look at the following resources: