The hash()
function in Python is used to return the hash value of an object. Hash values are integers used to quickly compare dictionary keys during a dictionary lookup. This function is particularly useful for ensuring the uniqueness of keys in dictionaries and for implementing hash-based collections such as sets and dictionaries.
Table of Contents
- Introduction
hash()
Function Syntax- Understanding
hash()
- Examples
- Hashing Immutable Types
- Using
hash()
with Custom Objects
- Real-World Use Case
- Conclusion
Introduction
The hash()
function computes the hash value of an object, which is an integer representing the object. Hash values are used internally by hash tables, such as those used in dictionaries and sets, to quickly compare keys and detect duplicates.
hash() Function Syntax
The syntax for the hash()
function is as follows:
hash(object)
Parameters:
- object: The object to be hashed. The object must be immutable, such as an integer, float, string, or tuple containing only immutable elements.
Returns:
- An integer hash value of the given object.
Raises:
- TypeError: If the object is not hashable (i.e., mutable objects like lists, dictionaries, or sets).
Understanding hash()
The hash()
function computes a hash value for an object, which is consistent within a single execution of a Python program but may vary across different executions. Hashable objects must have a __hash__()
method that returns an integer.
Examples
Hashing Immutable Types
To demonstrate the basic usage of hash()
, we will compute the hash values of various immutable types.
Example
# Hashing integers
print("Hash of 42:", hash(42))
# Hashing floats
print("Hash of 3.14:", hash(3.14))
# Hashing strings
print("Hash of 'hello':", hash("hello"))
# Hashing tuples
print("Hash of (1, 2, 3):", hash((1, 2, 3)))
Output:
Hash of 42: 42
Hash of 3.14: 322818021289917443
Hash of 'hello': -4454917197686575191
Hash of (1, 2, 3): 529344067295497451
Using hash()
with Custom Objects
This example shows how to use hash()
with custom objects by implementing the __hash__()
method.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __hash__(self):
return hash((self.name, self.age))
# Creating instances of Person
person1 = Person("Ravi", 25)
person2 = Person("Sita", 30)
# Hashing custom objects
print("Hash of person1:", hash(person1))
print("Hash of person2:", hash(person2))
Output:
Hash of person1: 5024004893253149648
Hash of person2: 5118765208014861181
Real-World Use Case
Using Hashes in Dictionaries
In real-world applications, the hash()
function is used to ensure the uniqueness of keys in dictionaries, allowing for efficient data retrieval.
Example
# Creating a dictionary with hashable keys
data = {
hash("apple"): "A sweet red fruit",
hash("banana"): "A long yellow fruit",
hash("cherry"): "A small red fruit"
}
# Retrieving values using hash values
print("Description of 'apple':", data[hash("apple")])
print("Description of 'banana':", data[hash("banana")])
Output:
Description of 'apple': A sweet red fruit
Description of 'banana': A long yellow fruit
Using Hashes in Sets
Hashes are also used in sets to ensure the uniqueness of elements.
Example
# Creating a set of hashable elements
fruits = {hash("apple"), hash("banana"), hash("cherry")}
# Adding a new element to the set
fruits.add(hash("date"))
# Checking if an element is in the set
print("Is 'apple' in the set?", hash("apple") in fruits)
print("Is 'mango' in the set?", hash("mango") in fruits)
Output:
Is 'apple' in the set? True
Is 'mango' in the set? False
Conclusion
The hash()
function in Python is used for computing hash values of immutable objects. By using this function, you can ensure the uniqueness of keys in dictionaries and elements in sets, making it particularly helpful in scenarios such as data retrieval, data storage, and implementing hash-based collections in your Python applications.