In How to hash lists? I was told that I should convert to a tuple first, e.g. [1,2,3,4,5]
to (1,2,3,4,5)
.
So the first cannot be hashed, but the second can. Why*?
*I am not really looking for a detailed technical explanation, but rather for an intuition
Because a list is mutable, while a tuple is not. When you store the hash of a value in, for example, a dict, if the object changes, the stored hash value won't find out, so it will remain the same.
All immutable built-in objects in Python are hashable like tuples while the mutable containers like lists and dictionaries are not hashable.
So, are tuples hashable or not? The right answer is: some tuples are hashable. The value of a tuple holding a mutable object may change, and such a tuple is not hashable. To be used as a dict key or set element, the tuple must be made only of hashable objects.
In Python, any immutable object (such as an integer, boolean, string, tuple) is hashable, meaning its value does not change during its lifetime. This allows Python to create a unique hash value to identify it, which can be used by dictionaries to track unique keys and sets to track unique values.
Mainly, because tuples are immutable. Assume the following works:
>>> l = [1, 2, 3] >>> t = (1, 2, 3) >>> x = {l: 'a list', t: 'a tuple'}
Now, what happens when you do l.append(4)
? You've modified the key in your dictionary! From afar! If you're familiar with how hashing algorithms work, this should frighten you. Tuples, on the other hand, are absolutely immutable. t += (1,)
might look like it's modifying the tuple, but really it's not: it simply creating a new tuple, leaving your dictionary key unchanged.
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