Why are tuples immutable?

Jeff Shannon jeff at ccvcorp.com
Tue Dec 21 19:50:45 CET 2004

Antoon Pardon wrote:

>Op 2004-12-17, Jeff Shannon schreef <jeff at ccvcorp.com>:
>>Now, even if hash were made to equal id... suppose I then pass that dict 
>>to a function, and I want to get the value that I've stored under 
>>[1,2].  In order to do that, I'd *also* have to pass in the *exact* list 
>>that I used as the key, because *only* that *exact* instance will hash 
>Maybe that is what I want.

Then use a class instance, rather than a list.  It's too valuable 
elsewhere to have lists that compare by value rather than identity.

>That doesn't change the fact that conceptually a programmer can use
>them that way. So do you think that if a programmer uses a list
>as a heap or a sorted list he should limit his object to immutable
>objects. Are you saying that programmers shouldn't sort mutable

I'm saying that your analogy of list/heap *values* to dictionary *keys* 
is a bogus analogy.  Dictionary *values* have no restrictions against 
mutation, just as list/heap values have no restrictions.

I'm also saying that a sorted/heaped list can be easily fixed by 
examining the items in it.  A broken hash table *cannot* be fixed that 

>>Note also that, if a list becomes unsorted or unheaped, it's fairly easy 
>>to resort or re-heapify the list.  It may take some time, but nothing is 
>>lost.  If a dictionary key mutates, then data *is* lost. 
>Is it? I don't see why an items method should fail to provide all (key,
>value) pairs even when keys were mutated.

How does the dict know which value is associated with which 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.  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.  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. 

Given that lists simply cannot replace every usage of tuples as 
dictionary keys, the question becomes only one of which is more 
important -- that lists compare to each other by value, or that lists 
are usable as dictionary keys.  Given the ease of using compare-by-ID 
class instances instead of lists, and the general usefulness of having 
lists compare by value, I think that Python made the right choice.

Jeff Shannon
Credit International

More information about the Python-list mailing list