From a recent SO question (see Create a dictionary in python which is indexed by lists) I realized I probably had a wrong conception of the meaning of hashable and immutable objects in python.
We could say that all immutable objects are hashable, because if the hash changes during the object's lifetime, then it means that the object mutated. But not quite. Consider a tuple which has a list (mutable). Some say tuple is immutable, but at the same time it is somewhat not hashable (throws).
An object is hashable if it has a hash value that does not change during its entire lifetime. Python has a built-in hash method ( __hash__() ) that can be compared to other objects. For comparing it needs __eq__() or __cmp__() method and if the hashable objects are equal then they have the same hash value.
In particular, all the primitive data types (strings, integers, floats, complex, boolean, bytes), ranges, frozensets, functions, and classes, both built-in and user-defined, are always hashable, while lists, dictionaries, sets, and bytearrays are unhashable.
Hashable data types: int , float , str , tuple , and NoneType .
Hashing is the process of converting some large amount of data into a much smaller amount (typically a single integer) in a repeatable way so that it can be looked up in a table in constant-time (O(1)
), which is important for high-performance algorithms and data structures.
Immutability is the idea that an object will not change in some important way after it has been created, especially in any way that might change the hash value of that object.
The two ideas are related because objects which are used as hash keys must typically be immutable so their hash value doesn't change. If it was allowed to change then the location of that object in a data structure such as a hashtable would change and then the whole purpose of hashing for efficiency is defeated.
To really grasp the idea you should try to implement your own hashtable in a language like C/C++, or read the Java implementation of the HashMap
class.
- Are there mutable objects that are hashable or immutable objects that are not hashable?
In Python, tuple is immutable, but it is hashable only if all its elements are hashable.
>>> tt = (1, 2, (30, 40)) >>> hash(tt) 8027212646858338501 >>> tl = (1, 2, [30, 40]) >>> hash(tl) TypeError: unhashable type: 'list'
Hashable Types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With