The hash()
function returns a unique integer (hash value) for an object. It’s useful for storing objects in hash-based collections like sets and dictionaries, ensuring data integrity, and optimizing lookups.
Example
num = 42
print(hash(num))
# Output: (Unique hash value)
Each immutable object gets a unique, fixed hash value.
Syntax
hash(object)
- object → The object to hash (must be immutable:
int
,float
,str
,tuple
). - Returns → A unique integer (hash value).
1. Hashing Strings for Fast Lookups
name = "Alice"
print(hash(name))
# Output: (Unique hash value)
Hashes make string comparisons faster in dictionaries.
2. Using hash()
in Sets and Dictionaries
Hashes allow fast indexing in sets and dictionary keys.
users = {"Alice", "Bob", "Charlie"}
print(hash("Alice") in map(hash, users))
# Output: True
This makes lookups faster than checking each item manually.
3. Hashing Tuples for Consistency
Immutable tuples can be hashed, unlike lists.
coords = (10, 20)
print(hash(coords))
# Output: (Unique hash value)
Useful when storing coordinates, database records, or cache keys.
4. Objects That Cannot Be Hashed
Mutable objects like lists and dictionaries cannot be hashed.
hash([1, 2, 3])
# TypeError: unhashable type: 'list'
Only immutable objects can be used as dictionary keys or set elements.
Key Notes
- ✔ Converts immutable objects into unique numbers for fast lookups.
- ✔ Used in sets and dictionary keys for quick comparisons.
- ✔ Tuples can be hashed, but lists cannot.
- ✔ Hash values may change across Python sessions (except for integers and strings).
By using hash()
, you can store and retrieve data efficiently, making it essential for fast data processing and unique object identification. 🚀