Append tuples to a tuples

Question:

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

Asked By: Hardy

||

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

Answered By: 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!

Answered By: 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.

Answered By: Roberto

in python both ((0,0)) and (0,0) are equal:

>>> x=((0,0))
>>> y=(0,0)
>>> x==y
True

so to get ((0,0)) you need to type ((0,0),)

Answered By: suhailvs
>>> 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

Answered By: Arun
>>> x = *x, (8, 9); x
((1, 2), (3, 4), (5, 6), (8, 9))

This way you could avoid using the + operator, the += operator, and that weird ((8, 9),) syntax. Using the deconstruct operator * is a bit more elegant and slightly more obvious what you want to have happen: deconstruct previous tuple, appending new element onto new tuple, x.

Answered By: TimF
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.