Why are tuples immutable?

Jeff Shannon jeff at ccvcorp.com
Wed Dec 22 13:12:25 EST 2004


Antoon Pardon wrote:

>Op 2004-12-21, Jeff Shannon schreef <jeff at ccvcorp.com>:
>  
>
>How does the dict know which value is associated with which key? 
>  
>
>
>Because there is a link between the key and the value. The problem
>with a mutated key in a dictionary is not that the link between the
>key and the value is severed, but that the key hashes now to a different
>bucket. But if you just go over the buckets and iterate over the keys
>within and there associated values, you will encouter your mutated
>key with its value.
>  
>

Except that the hash value *IS* the link between the key and the value.  
You cannot change the hash value without severing the link.  You cannot 
trace the link without the original hash value.  You do not have the 
original hash value when accessing the dict with a mutated key.

>>I need to be able to access sequence-keyed dictionaries with literals, 
>>which means that the keys need to compare by value, not ID.  Thus, I 
>>need to have sequences that compare (and hash) by value.  These 
>>conditions *cannot* be met by a mutable list.
>>    
>>
>
>Which condition can't be met by a mutable list? The only ones I see
>above is comparison and hashable by value. A list can be compared
>and hashed by value.
>  
>

A list cannot be hashed by value in such a way that the hash doesn't 
change when the list mutates.

>>I can have the quality of 
>>hash value not changing when mutated, or I can have the quality of 
>>hashing by value, but I *cannot* have both.
>>    
>>
>
>So? You don't need the first.
>  
>

That's an "interesting" assertion.  You have yet to provide any evidence 
of it, however. 

>>Thus, even if you make 
>>lists hash by ID, I *still* need to have an immutable tuple type so that 
>>I can get hash-by-value. 
>>    
>>
>
>No you don't. The same algorithm that works for hashing tuples will
>work just as fine for hashing lists.
>  
>

Except that the hash value will change when the list mutates, and then I 
can't access my dictionary values.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list