Tuples and immutability

Zachary Ware zachary.ware+pylist at gmail.com
Thu Feb 27 11:47:09 EST 2014


On Thu, Feb 27, 2014 at 10:27 AM, Eric Jacoboni <eric.jacoboni at gmail.com> wrote:
> Le 27/02/2014 17:13, Zachary Ware a écrit :
>>
>> You're not the first person to have this question :)
>>
>> http://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works
>>
>
> Oh yes, i was aware of this explanation (thanks to Chris for his answer,
> too)... and that's why i wrote "reasonable" :)
> I know i should use append() or extend() and i understand the tricky
> implications of += in this context. But, imho, it's far from being a
> intuitive result, to say the least.

Well, once you understand what's actually going on, it's the result
that you should expect.  The FAQ entry I linked to exists to help
people get to that point.

To answer your specific questions:

> But, then, why a_tuple is still modified?

It is not.  a_tuple is still "('spam', <list object at specific
address>, 'eggs')", exactly the same before and after the attempted
"a_tuple[1] += [20]".  The change is internal to <list object at
specific address>.

> I get a TypeError for an illegal operation, but this operation is still
> completed?

Half completed.  The extension of <list object at specific address>
happened as expected, but the assignment of <list object at specific
address> to a_tuple[1] didn't.  It looks like it did, though, because
the assignment was just trying to assign the same object to the same
index.

-- 
Zach



More information about the Python-list mailing list