list in a tuple

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Dec 28 01:34:00 EST 2007


En Thu, 27 Dec 2007 16:38:07 -0300, <montyphyton at gmail.com> escribió:
> On Dec 27, 8:20 pm, Wildemar Wildenburger
> <lasses_w... at klapptsowieso.net> wrote:
>>  >
>>
>>  From that post:
>>  > Ok, I do admit that doing
>>  >
>>  > a = ([1], 2)
>>  > a[0].append(2)
>>  >
>>  > also doesn't throw an error, but this only confuses me more.
>>  >
>> Why? You mutate thelist, but thetupledoes not change. It is still  
>> atupleof alistand an int. At least that's how I think about it, and I
>> seem to recall reading that beavior justified like this (don't ask me
>> where though (might have been "Dive Into Python", but maybe not)).
>
> That part is ok, I mean it doesn't confuse me I just wanted to say
> that this is somewhat confusing behavior.
> I agree that its not best put... But I was thinking about the last
> part of the post, the part
> that talks about trying to print a tuple and getting an error.

Instead of trying to explain it myself, I'll refer you to this little  
essay [1] by Michael Hudson including some nice ASCII art, and a long  
reply from Alex Martelli from which I'll quote just a few memorable  
paragraphs. (Just replace "dictionary" with "tuple" in your example)

"""There is [...] a huge difference
between changing an object, and changing (mutating) some
OTHER object to which the first refers.

In Bologna over 100 years ago we had a statue of a local hero
depicted pointing forwards with his finger -- presumably to
the future, but given where exactly it was placed, the locals
soon identified it as "the statue that points to Hotel
Belfiore".  The one day some enterprising developer bought
the hotel's building and restructured it -- in particular,
where the hotel used to be was now a restaurant, Da Carlo.

So, "the statue that points to Hotel Belfiore" had suddenly
become "the statue that points to Da Carlo"...!  Amazing
isn't it?  Considering that marble isn't very fluid and the
statue had not been moved or disturbed in any way...?

This is a real anecdote, by the way (except that I'm not
sure of the names of the hotel and restaurant involved --
I could be wrong on those), but I think it can still help
here.  The dictionary, or statue, has not changed at all,
even though the objects it refers/points to may have been
mutated beyond recognition, and the name people know it
by (the dictionary's string-representation) may therefore
change.  That name or representation was and is referring
to a non-intrinsic, non-persistent, "happenstance"
characteristic of the statue, or dictionary...
"""

[1] http://python.net/crew/mwh/hacks/objectthink.html

-- 
Gabriel Genellina




More information about the Python-list mailing list