Why are tuples immutable?

Antoon Pardon apardon at forel.vub.ac.be
Thu Dec 16 11:42:15 CET 2004

Op 2004-12-16, Paul Rubin schreef <http>:
> Antoon Pardon <apardon at forel.vub.ac.be> writes:
>> Two guidelines can make it easier for a programmer to do this.
>> 1) Put a copy in the dictionary, so that mutating the original
>>    object won't affect what is in the dictonary.
> What's supposed to happen here?
>     a = [1,2,3]
>     d[a] = 9
>     a.append(4)
>     print d[a]
> It doesn't sound like good dictionary semantics to me.

That depends on whether the programmes wants value equality
or identity equality.

In the first case the programmer shouldn't mutate a after
it was introduced as key in the dictionary; but should
either introduce a copy or work on a copy later. As
such your snippet of code would become.

  a = [1,2,3]
  d[a[:]] = 9
  print d[a]

And this would raise a KeyError, unless the list [1,2,3,4]
would be in the dictionary.

In the second case your code would produce 9.

Antoon Pardon

More information about the Python-list mailing list