The hash() function in Python returns an integer hash value for an object. This hash value is mainly used internally by Python to store and quickly compare keys in hash-based data structures like dictionaries and sets. Only immutable objects can be hashed.
Example: This example shows how hash() generates hash values for common immutable data types like integers and strings.
print(hash(10))
print(hash("python"))
Output
10 -5941299646830648578
Explanation:
- hash(10) returns 10 because integers hash to themselves
- hash("python") returns a generated integer based on the string content
Syntax
hash(obj)
- Parameters: obj - The object to be hashed (must be immutable)
- Returns: An integer hash value if the object is hashable
Examples
Example 1: This example demonstrates how hash() works with immutable objects like integers, strings and floats.
a = 5
b = "data"
c = 3.14
print(hash(a))
print(hash(b))
print(hash(c))
Output
5 1402671398882199705 322818021289917443
Explanation:
- hash(a), hash(b), and hash(c) return integer hash values
- All objects used are immutable, so hashing is allowed
Example 2: This example compares hashing a tuple (immutable) and a list (mutable).
t = (1, 2, 3)
l = [1, 2, 3]
print(hash(t))
print(hash(l))
Output
529344067295497451
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
TypeError: unhashable type: 'list'
Explanation:
- hash(t) works because tuples are immutable
- hash(l) fails because lists are mutable and not hashable
Example 3: This example shows how to make a custom class hashable by defining __hash__() and __eq__().
class Emp:
def __init__(self, name, eid):
self.name = name
self.eid = eid
def __eq__(self, other):
return self.name == other.name and self.eid == other.eid
def __hash__(self):
return hash((self.name, self.eid))
e1 = Emp("Amit", 101)
e2 = Emp("Amit", 101)
print(hash(e1))
print(hash(e2))
Output
-6335375878290967053 -6335375878290967053
Explanation:
- hash((self.name, self.eid)) creates a hash from immutable values
- Objects with equal data produce the same hash value
Example 4: This example shows why hashable objects are required as dictionary keys. Only immutable objects can be used as keys because Python relies on their hash values.
d = {}
k1 = (1, 2)
k2 = [1, 2]
d[k1] = "tuple key"
d[k2] = "list key"
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 6, in <module>
TypeError: unhashable type: 'list'
Explanation:
- k1 works as a key because tuples are immutable and hash(k1) is valid
- k2 fails because lists are mutable and hash(k2) is not allowed