"1,+2,", but not "(1,)+2,"

MRAB python at mrabarnett.plus.com
Fri Jul 31 11:16:08 EDT 2020


On 2020-07-31 14:15, Jon Ribbens via Python-list wrote:
> On 2020-07-31, Stefan Ram <ram at zedat.fu-berlin.de> wrote:
>>   You can write
>>
>>|>>> 1,+2,
>>|(1, 2)
>>
>>   , but not
>>
>>|>>> (1,)+2,
>>|TypeError: can only concatenate tuple (not "int") to tuple
>>
>>   . Why? (Python 3.9)
> 
> For the obvious reason, as indicated by the error message?
> 
> What are you expecting these expressions to mean?
> 
(For some reason, I haven't received Stefan's original post.)

It's all to do with operator precedence.

The '+' has a higher precedence than the ',', so:

     1,+2,

is parsed as:

     (1),(+2),

NOT as:

     (1,)+(2,)

although they happen to give the same answer.

On the other hand:

     (1,)+2,

is parsed as:

     ((1,)+2),

which results in a TypeError.


More information about the Python-list mailing list