![]() |
VOOZH | about |
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.
10 -5941299646830648578
Explanation:
hash(obj)
Example 1: This example demonstrates how hash() works with immutable objects like integers, strings and floats.
5 1402671398882199705 322818021289917443
Explanation:
Example 2: This example compares hashing a tuple (immutable) and a list (mutable).
Output
529344067295497451
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
TypeError: unhashable type: 'list'
Explanation:
Example 3: This example shows how to make a custom class hashable by defining __hash__() and __eq__().
-6335375878290967053 -6335375878290967053
Explanation:
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.
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 6, in <module>
TypeError: unhashable type: 'list'
Explanation: