When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?

Thomas Nelson thn at mail.utexas.edu
Tue Apr 24 17:46:13 EDT 2007


On Apr 23, 10:38 pm, Mel Wilson <mwil... at the-wire.com> wrote:
> Neil Cerutti wrote:
> > The interpreter explains it: "A list is not a hashable object."
> > Choosing a hash table instead of some kind of balanced tree seems
> > to be just an optimization. ;)
>
> Even with a balanced tree, if a key in a node changes value, you may
> have to re-balance the tree.  Nothing in a Python list says that a
> dictionary tree would have to be re-balanced if you changed that
> particular list.
>
>         Mel.

You don't have to look at any implementation.  A dictionary maps every
key to exactly one object.  If the objects were mutable, you could
change one key to another key, and then which item would the
dictionary pull?
(Imaginary code)
d = {[1,2,3]: 'hat', [1,2,4]: 'sock' }
for key in d:
    key.pop()
print d[[1,2]]  #does this print hat or sock?

Sets have the same problem.  A set can't have duplicates; how could
you enforce this with mutable objects?

Tom




More information about the Python-list mailing list