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))
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)
.
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!
[PLEASE SEE NOTE BELOW]
Also this should work:
x += (0,0),
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.
>>> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With