How to extend a tuple of tuples?
Steve D'Aprano
steve+python at pearwood.info
Fri Sep 9 06:07:41 EDT 2016
On Fri, 9 Sep 2016 04:47 pm, Frank Millman wrote:
> Hi all
>
> This should be easy, but I cannot figure it out.
>
> 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 -
>
> ((1, 2), (3, 4), (5, 6))
a = a + ((5, 6),)
You might think that you can just add (5, 6) but that doesn't work:
py> a + (5, 6)
((1, 2), (3, 4), 5, 6)
The plus operator builds a new tuple containing the contents of each of the
two tuples concatenated, so to get the result that you want you need a
tuple containing (5, 6) as the one and only item. Because that's a tuple
with one item, you need a trailing comma:
py> len( ((5, 6),) )
1
py> a + ((5, 6),)
((1, 2), (3, 4), (5, 6))
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list