How to extend a tuple of tuples?

BartC bc at freeuk.com
Mon Sep 12 17:19:49 EDT 2016


On 12/09/2016 21:31, Thomas 'PointedEars' Lahn wrote:
> Ben Finney wrote:
>
>> "Frank Millman" <frank at chagford.com> writes:
>>> Assume you have a tuple of tuples -
>>>
>>> a = ((1, 2), (3, 4))
>>>
>>> You want to add a new tuple to it, so that it becomes
>>
>> As you acknowledge, the tuple ‘a’ can't become anything else. Instead,
>> you need to create a different value.
>
> Wrong.
>
>>> The obvious way does not work -
>>>
>>> a += (5, 6)
>>>
>>>    ((1, 2), (3, 4), 5, 6)
>                      ^^^^^^
>> Right, because a tuple is immutable.
>
> How did you get that idea?  It has been mutated in the very statement that
> you are quoting,

By the same argument, then strings and ints are also mutable.

Here, the original tuple that a refers to has been /replaced/ by a new 
one. The original is unchanged. (Unless, by some optimisation that 
recognises that there are no other references to it, the original is 
actually appended to. But in general, new objects are constructed when 
implementing +=.)

-- 
Bartc



More information about the Python-list mailing list