Help understanding the decisions *behind* python?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Jul 22 02:45:54 EDT 2009


On Tue, 21 Jul 2009 06:49:59 -0700, Inky 788 wrote:

> On Jul 20, 12:27 pm, Phillip B Oldham <phillip.old... at gmail.com> wrote:
>> [snip] We
>> understand that lists are mutable and tuples are not, but we're a
>> little lost as to why the two were kept separate from the start. They
>> both perform a very similar job as far as we can tell.
> 
> My guess is that it was probably for optimization reasons long ago. I've
> never heard a *good* reason why Python needs both.

Suppose you could do this:

key = [1, 2]
adict = {key: 'x', [1, 1]: 'y'}

This would work as expected:

adict[ [1, 2] ]
=> returns 'x'

adict[ [1, 1] ]
=> returns 'y'

But what happens if you mutate the key?

key[1] = 0
adict[ [1, 2] ]
=> raises KeyError

Okay, that's bad. What's even worse is this:

key[1] = 1
adict[ [1, 1] ]
=> should it return 'x' or 'y'?


The solution is to disallow mutable objects like lists from being used as 
keys in dicts, and to allow immutable list-like tuples instead.



-- 
Steven



More information about the Python-list mailing list