user2988310
user2988310

Reputation: 51

why can't I concatenate these two tuples?

I am trying to concatenate two tuples using the overloaded + operator in Python 3.6. I don't have an issue if I include the parenthesis like the first example, but if I leave off the parenthesis as in the second example, I get an error. The message I get is "bad operand type for unary +: 'tuple'". Can anyone explain what is happening?

newtup = (3,) + (2,4)

newtup = 3, + (2,4)

Upvotes: 1

Views: 199

Answers (5)

Vishvajit Pathak
Vishvajit Pathak

Reputation: 3731

Unary operator + expects valid a operand (int, float etc) on the right side.

In your code 3, + (2, 4), you are providing a tuple (2, 4) as an operand to + which is not a valid operand and so is the error.

In your code:

newtup = (3,) + (2, 4)

These are 2 separate tuples (3,) and (2,4), so it works.

newtup = 3, + (2, 4)

Here its a single tuple with 2 elements 3 and +(2, 4) which fails due to above mentioned reason.

Upvotes: 0

Herc01
Herc01

Reputation: 622

Simple; On the first line you are creating a new tuple made of 2 tuples. On the second line you are adding an int to a tuple. Check this out.

 x, y=3, (2,4) # assign  x and y to 3, and (2,4) respectively
 print type(y), type(x)
 <type 'tuple'> <type 'int'> 

Upvotes: -1

U13-Forward
U13-Forward

Reputation: 71610

As you're doing:

3, + (2,4)

It basically simplifies to two parts 3, and +(2,4), the second is invalid so you can try new-unpacking in python 3:

(3,*(2,4))

If on python2 just use second example.

Upvotes: 0

Nicholas Pipitone
Nicholas Pipitone

Reputation: 4152

It's trying to parse the second line as

(3, + (2,4))

Then, it's seeing that you used the unary +, as in a = +5, with a tuple. This isn't allowed, and thus you get an error. Commas are given very wide precedence (ie they consume as many characters as possible, closer to a + than a *). The reason behind this is that (biglongexpression1, biglongexpression2) should never mix the two biglongexpressions. Everything else is more important and should be evaluated before a comma, and thus +(2,4) is evaluated before the comma - because it's a biglongexpression.

Upvotes: 3

user2357112
user2357112

Reputation: 281585

It's a precedence issue. 3, + (2, 4) is parsed as a tuple with elements 3 and +(2, 4), not as adding 3, and (2, 4). You need the parentheses.

Upvotes: 4

Related Questions