4

I have a tuple:

a = (1,2,3)

and I need to add a tuple at the end

b = (4,5)

The result should be:

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

Even if I wrap b in extra parents: a + (b), I get (1,2,3,4,5) which is not what I wanted.

1
  • Remember, the comma inside the brackets is very important, like in my answer, it should have been a + (b,). Otherwise Python will consider (b) as simply b wrapped in brackets. The comma makes it a tuple. Commented Feb 18, 2014 at 14:50

3 Answers 3

12

When you do a + b you are simply concatenating both the tuples. Here, you want the entire tuple to be a part of another tuple. So, we wrap that inside another tuple.

a, b = (1, 2, 3), (4,5)
print a + (b,)  # (1, 2, 3, (4, 5))
0
3
>>> a = (1,2,3)
>>> b = (4,5)
>>> a + (b,)
(1, 2, 3, (4, 5))
1

tuple objects are immutable. The result you're getting is a result of the fact that the + (and +=) operator is overridden to allow "extending" tuples the same way as lists. So when you add two tuples, Python assumes that you want to concatenate their contents.

To add an entire tuple onto the end of another tuple, wrap the tuple to be added inside another tuple.

c = a + (b,) # Add a 1-tuple containing the tuple to be added.
print(c) # >>> (1, 2, 3, (4, 5))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.