How are the properties of a hash function related to the mutability or immutability of data types?
sobes.tech AI
Answer from AI
A hash function in programming returns a numerical value (hash) that uniquely identifies the content of an object. For proper functioning, especially in dictionaries and sets, it is important that the hash of an object does not change during its lifetime.
This is directly related to the immutability of the data type. If an object is mutable, its internal state can change, and consequently, its hash can also change. This will lead to errors when searching for the object in hash tables, as the object will end up in the 'wrong' bucket.
Therefore, in Python, objects used as keys in dictionaries or elements of sets must be immutable and have a stable hash. For example, tuples are immutable and hashable, while lists are mutable and not hashable.
Example:
# Tuple - immutable and hashable
t = (1, 2, 3)
print(hash(t)) # Works
# List - mutable and not hashable
l = [1, 2, 3]
print(hash(l)) # Error: TypeError: unhashable type: 'list'