bad operand type for unary +: tuple

Diez B. Roggisch deets at nospam.web.de
Thu Oct 22 09:23:21 EDT 2009


Frank Millman wrote:

> Hi all
> 
> This is just out of curiosity.
> 
> I have a tuple, and I want to create a new tuple with a new value in the
> first position, and everything else unchanged.
> 
> I figured out that this would work -
> 
>>>> t = ('a', 'b', 'c')
>>>> t2 = ('x',) + t[1:]
>>>> t2
> ('x', 'b', 'c')
> 
> Then I thought I would neaten it a bit by replacing "('x',)" with "'x',"
> on the assumption that it is not necessary to surround a tuple with
> brackets.
> 
> This is the result -
> 
>>>> t = ('a', 'b', 'c')
>>>> t2 = 'x', + t[1:]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: bad operand type for unary +: 'tuple'
>>>>
> 
> It is not a problem - I will just stick to using the brackets. However, I
> would be interested to find out the reason for the error.
> 
> Version is 2.6.2.
> 
> Thanks

the operator precedence. Sure you want to write

 (a, -b, c)

to form a tuple with a negated (or actually all other kinds of expressions)
value in it. So python made -/+ and more or less all other operators
precede the comma, which is the actual tuple-operator. And consequently, 

a, +(c, d)

tries to *first* apply + to the tuple (c, d) - which isn't defined.

Diez





More information about the Python-list mailing list