Parens do create a tuple

Steven D'Aprano steve at pearwood.info
Sun Apr 10 22:32:08 EDT 2016


On Mon, 11 Apr 2016 11:41 am, Ben Finney wrote:

> Chris Angelico <rosuav at gmail.com> writes:
> 
>> Fair enough. Let's instead say "commas create tuples", which is true
>> in all cases except the singleton empty tuple. Is that near enough
>> that we can avoid the detail?
> 
> It's a fine thing to say, because it's simply true. Commas create
> tuples.

def func(arg1, arg2, arg3):
    pass

func(1, 2, 3) 

does not create a tuple (1, 2, 3) anywhere in its execution. So there are
commas that don't create a tuple. Including these:

import math, sys, time

# Python 2
print "This", "is", "not", "a", "tuple."

# Also Python 2
try:
    ...
except Exception, err:
    ...

# Any Python
del fe, fi, fo, fum



Live by pedantry, die by pedantry.

:-)


> To say “commas create tuples” is to say an unobjectionably true
> statement about Python syntax. It remains true as one continues to learn
> Python.

Really not.


> To say “parens do not create tuples” is to lay a trap which needs to be
> de-fused at some point. Better IMO never to lay that trap.

If one wishes to be both pedantic and correct, as well as long-winded and
verbose, one needs to say something like this:


In the statement

    mytuple = (1, 2, 3, 4, 5)

it is not the parentheses or round brackets which creates the tuple, it is
the commas, so this will work equally well:

    mytuple = 1, 2, 3, 4, 5


In general, you create tuples in an expression by separating the values with
commas, not by surrounding them in parentheses. Parens act to group
expressions, so they're useful for ambiguous cases such as nested tuples:

    mytuple = 1, 2, 3, (10, 20, 30), 5

or to overrule the default precedence rules:

    lambda x, y: x+1, y+2  # a tuple of (lambda, y+2)

    lambda x, y: (x+1, y+2)  # a function that returns a tuple (x+1, y+2)


or just to make the expression look nicer. As a consequence, a single item
tuple can be created with a trailing comma, with or without parens:

    mytuple = 1,
    mytuple = (1,)


The zero-element tuple is a special case. You can't have a comma on its own,
so the zero-element tuple has its own special syntax:

    mytuple = ()



-- 
Steven




More information about the Python-list mailing list