How to extend a tuple of tuples?
Ben Finney
ben+python at benfinney.id.au
Fri Sep 9 03:42:39 EDT 2016
"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.
> 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)])
--
\ “Look at it this way: Think of how stupid the average person |
`\ is, and then realise half of 'em are stupider than that.” |
_o__) —George Carlin, _Doin' It Again_, 1990 |
Ben Finney
More information about the Python-list
mailing list