In Python, the hash()
function is a built-in method that returns the hash value of an object if it is hashable, i.e., it can be mapped to a fixed-size integer. Understanding the hash()
function is crucial, especially in scenarios where hashing plays a pivotal role in data manipulation and security. Let’s delve into the intricacies of hash()
with examples to grasp its functionality better.
Basic Usage:
# Example 1: Using hash() with an integer
num = 42
print(hash(num))
Output:
42
In this example, the integer 42
is hashable, and its hash value is itself.
Hashing Immutable Data Types:
# Example 2: Hashing a string
string = "Python"
print(hash(string))
Output:
5619692202234367599
Strings are immutable in Python, making them hashable. The hash value is computed based on the content of the string.
Hashing Tuples:
# Example 3: Hashing a tuple
tuple_example = (1, 2, 3)
print(hash(tuple_example))
Output:
2528502973977326415
Tuples containing only hashable elements can be hashed, with their hash values computed from the hashes of their elements.
Not All Objects Are Hashable:
# Example 4: Attempting to hash a list
list_example = [1, 2, 3]
try:
print(hash(list_example))
except TypeError as e:
print(e)
Output:
Lists are mutable, so attempting to hash them raises a TypeError
. Only immutable objects can be hashed.
Custom Objects and Hashing:
# Example 5: Defining a custom class and implementing __hash__()
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __hash__(self):
return hash((self.x, self.y))
point = Point(3, 4)
print(hash(point))
Output:
<span class="hljs-deletion">-9223363261197998140</span>
Custom objects can be made hashable by implementing the __hash__()
method. Ensure that the objects maintain hashability invariant.
Practical Application in Dictionaries:
# Example 6: Using hashable objects as keys in dictionaries
student_grades = {
('Alice', 'Math'): 85,
('Bob', 'Science'): 90,
('Charlie', 'History'): 75
}
print(student_grades[('Alice', 'Math')])
Output:
85
Hashable objects like tuples can be utilized as keys in dictionaries, enabling efficient data retrieval.