How to extend a tuple of tuples?

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Fri Sep 9 03:57:04 EDT 2016


Ben Finney writes:

> Frank Millman 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.
>
>> The obvious way does not work -
>>
>> a += (5, 6)
>>
>>    ((1, 2), (3, 4), 5, 6)
>
> Right, because a tuple is immutable.
>
> So instead, you want a different tuple. You do that by creating it,
> explicitly constructing a new sequence with the items you want::
>
>     b = tuple([
>             item for item in a
>             ] + [(5, 6)])

b = tuple(list(a) + [(5,6)])

b = a + tuple([(5,6)])

b = a + ((5,6),)

b = tuple(itertools.chain(iter(a), iter(((5,6),)))) # :))))



More information about the Python-list mailing list