Why are tuples immutable?
Antoon Pardon
apardon at forel.vub.ac.be
Thu Dec 16 06:25:31 EST 2004
Op 2004-12-16, Fredrik Lundh schreef <fredrik at pythonware.com>:
> Antoon Pardon wrote:
>
>> 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
>> a.append(4)
>> 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.
>
> how does the dictionary know if you want key value equality or key
> identity equality?
By the __hash__ and __eq__ methods you provide on your object.
--
Antoon Pardon
More information about the Python-list
mailing list