Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List unhashable, but tuple hashable?

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

like image 461
gsamaras Avatar asked May 10 '16 11:05

gsamaras


People also ask

Why list is Unhashable and tuple is hashable?

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.

Is a tuple of lists hashable?

All immutable built-in objects in Python are hashable like tuples while the mutable containers like lists and dictionaries are not hashable.

Is a tuple of tuples 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.

What does it mean that tuples are hashable?

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.


1 Answers

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.

like image 184
val Avatar answered Sep 19 '22 03:09

val