Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append tuples to a tuples

I can do append value to a tuples

>>> x = (1,2,3,4,5)
>>> x += (8,9)
>>> x
(1, 2, 3, 4, 5, 8, 9)

But how can i append a tuples to a tuples

>>> x = ((1,2), (3,4), (5,6))
>>> x
((1, 2), (3, 4), (5, 6))
>>> x += (8,9)
>>> x
((1, 2), (3, 4), (5, 6), 8, 9)
>>> x += ((0,0))
>>> x
((1, 2), (3, 4), (5, 6), 8, 9, 0, 0)

How can i make it

((1, 2), (3, 4), (5, 6), (8, 9), (0, 0))

like image 766
Hardy Avatar asked Dec 06 '13 04:12

Hardy


4 Answers

x + ((0,0),)

should give you

((1, 2), (3, 4), (5, 6), (8, 9), (0, 0))

Python has a wonky syntax for one-element tuples: (x,) It obviously can't use just (x), since that's just x in parentheses, thus the weird syntax. Using ((0, 0),), I concatenate your 4-tuple of pairs with a 1-tuple of pairs, rather than a 2-tuple of integers that you have in (0, 0).

like image 109
Amadan Avatar answered Oct 17 '22 11:10

Amadan


Add an extra parentheses:

>>> x = ((1,2), (3,4), (5,6)) + ((8,9),)
>>> x
((1, 2), (3, 4), (5, 6), (8, 9))

Notice the trailing comma. This will make you add a new-pair tuple to it.

Also, just a note: This is not appending, since tuples are immutable. You're creating a completely whole new tuple.

Hope this helps!

like image 28
aIKid Avatar answered Oct 17 '22 10:10

aIKid


[PLEASE SEE NOTE BELOW]

Also this should work:

x += (0,0),

NOTE:

this is unsafe!! Thanks to Amadan and aIKid for the great discussion.

As Amadan pointed out, this specific case will work only because the assignment operator += has lower priority than ,, so by the time the two tuples are joined, (0,0), has already become ((0,0),).

But if you try:

((1, 2), (3, 4)) + (5, 6),

the result will be a messy

(((1, 2), (3, 4), 5, 6),)

because + has higher priority than ,, so the numbers 5 and 6 are joined to the tuple separately! There intermediary stage is then ((1, 2), (3, 4), 5, 6), and finally this tuple with a final , is "corrected" to give (((1, 2), (3, 4), 5, 6),).

Take-home message: using the notation (5, 6), is not safe because it being "corrected" to ((5, 6),) might have lower priority than other operators.

like image 3
Roberto Avatar answered Oct 17 '22 12:10

Roberto


>>> x = ((1,2), (3,4), (5,6))

>>> x += ((8,9),)

>>> x

((1, 2), (3, 4), (5, 6), (8, 9))

>>> x += ((10,11),(12,13))

>>> x

((1, 2), (3, 4), (5, 6), (8, 9), (10, 11), (12, 13))

To represent a tuple with a single element, you have to use a trailing comma. And unlike list, tuple is immutable

like image 1
Arun Avatar answered Oct 17 '22 12:10

Arun