How to extend a tuple of tuples?
Ned Batchelder
ned at nedbatchelder.com
Mon Sep 12 22:52:49 EDT 2016
On Monday, September 12, 2016 at 4:31:37 PM UTC-4, Thomas 'PointedEars' Lahn wrote:
> Ben Finney wrote:
> > 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)])
>
> The correct approach is
>
> | >>> a += (5, 6),
> | >>> a
> | ((1, 2), (3, 4), (5, 6))
>
> The problem here is an ambiguity in the Python grammar where “(5, 6)” is
> _not_ parsed as a double, but as a list of singles. The ambiguity is
> resolved by adding a trailing comma.
There is no ambiguity in "(5, 6)". It is a tuple of two ints. To make
a sequence of tuples (albeit a one-element sequence), you add a comma
to make it a one-element tuple, which is the same as "((5,6),)".
> (This is basic Python knowledge.)
Considering the gaps in your own Python knowledge, please try not
to be condescending when answering questions here.
For a discussion of mutability and immutability in Python, which will
help with the other part of the discussion, you might like:
http://nedbatchelder.com/text/names1.html
--Ned.
More information about the Python-list
mailing list