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. Hashes of
strandbytesobjects are salted with a random seed, so they stay consistent within a single Python session but vary between sessions for security reasons. Hashes of other types, such as numbers, are stable across sessions.
hash() Examples
>>> hash("Real Python")
-7029269592779926217
The hash() function salts string hashes with a per-process random seed, so your output will differ. You’ll see a different integer each time you start a new interpreter.
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.
Note: hash() truncates the value returned by a custom .__hash__() to the host machine’s bit width, which sys.hash_info.width reports. A .__hash__() meant to interoperate across 32-bit and 64-bit builds shouldn’t assume a 64-bit result.
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:
- Dictionaries in Python (Tutorial)
- Sets in Python (Tutorial)
- Build a Hash Table in Python With TDD (Quiz)
- Using Dictionaries in Python (Course)
- Dictionaries in Python (Quiz)
- Using Sets in Python (Course)
- Python Sets (Quiz)