hash()
The built-in hash()
function returns an integer hash value for a given object, acting as a digital fingerprint for the object.
This hash value is used to quickly compare dictionary keys during dictionary lookups, ensuring that objects that compare equal 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 that represents 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
- Ensuring data integrity
- Supporting custom objects in sets and dictionaries
hash()
Real-World Example
Suppose you want to check if two files are identical. You can read their contents and use the hash()
function to compare their hash values:
def are_files_identical(file1, file2):
with open(file1, "rb") as f1, open(file2, "rb") as f2:
return hash(f1.read()) == hash(f2.read())
# Usage
if are_files_identical('file1.txt', 'file2.txt'):
print("The files are identical.")
else:
print("The files are different.")
This approach quickly checks file equality by comparing hash values, which is more efficient than comparing the files byte by byte.
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).