[Tutor] Fwd: Difference between types

Dave Angel davea at davea.name
Fri May 24 21:10:59 CEST 2013


On 05/24/2013 02:53 PM, Albert-Jan Roskam wrote:
> <snip>
>
>> A tuple is defined by commas, depending on context. However,
>> parentheses are typically required because commas have low precedence.
>>
>>      >>> 1, 2 + 3, 4
>>      (1, 5, 4)
>>
>>      >>> (1, 2) + (3, 4)
>>      (1, 2, 3, 4)
>>
>> An empty tuple is a special case:
>>
>>      >>> x = ()
>>      >>> type(x)
>>      <type 'tuple'>
>
> Why do I need to use a trailing comma to create a singleton tuple? Without a comma it seems to mean "parenthesized single object", ie the parentheses are basically not there.
>>>> type((0,))
> <type 'tuple'>
>>>> type((0))
> <type 'int'>
>>>> (0)
> 0
>>>> x = (,)
> SyntaxError: invalid syntax
>
>>>> (0,0)
> (0, 0)
>

Your answer is right above your question, in the part you quoted 
(without attribution) from eryksun.

The empty tuple is specified with ().  But for any tuple with one or 
more members, it's the commas that turn it into a tuple.  The parens are 
not necessarily needed unless the statement is complex enough that we 
need them for precedence.

So   x = 3,4

makes a one-tuple out of 3 and 4.  If you want a one-tuple (which is NOT 
a singleton), you need a silly-looking comma to specify it:
      x = 5,

In other words, comma is the operator, not parentheses.  Parentheses are 
used to change precedence (as well as for function parameters and 
arguments.)

Note that one thing that confuses newcomers is the dual use of commas 
and parens for functions.  If you need a literal tuple as a function 
argument, you will need extra parens so the comma aimed at the tuple 
doesn't get confused with the comma used to separate arguments.

-- 
DaveA


More information about the Tutor mailing list