bad operand type for unary +: tuple

F

Frank Millman

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):

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

Frank Millman
 
D

Diez B. Roggisch

Frank said:
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):

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
 
F

Frank Millman

Diez said:
Frank said:
t = ('a', 'b', 'c')
t2 = 'x', + t[1:]
Traceback (most recent call last):


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.

Makes total sense. Thanks, Diez

Frank
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top