Parens do create a tuple (was: one-element tuples [Was: Most probably a stupid question, but I still want to ask])

Chris Angelico rosuav at gmail.com
Sun Apr 10 20:50:36 EDT 2016


On Mon, Apr 11, 2016 at 10:45 AM, Ben Finney <ben+python at benfinney.id.au> wrote:
> So the expanation that remains true when you examine it is: People
> wanted a literal syntax to create a zero-length tuple. A pair of parens
> is that literal syntax, and it's the parens that create the (empty)
> tuple.

But parens do NOT create a one-element tuple, and that's usually where
people trip up. If you show someone this line of code:

x = ()

and ask what x will be, you might get some wrong responses, but you'll
get a lot of people correctly deducing that it's a tuple. The problem
is that people see this progression:

x = ()
y = (1)
z = (1, 2)

and assume they're all tuples. A better progression is this:

x = ()
y = (1,)
z = (1, 2,)

where every element is followed by a comma and every tuple is
surrounded by parentheses. In that situation, everything works. There
are slightly different rules about which parts are optional (the
parens everywhere except the first case, and the last comma everywhere
except the second), but this should be the basic form of tuple
progression.

ChrisA



More information about the Python-list mailing list