0

This question is more about "appending" new items to a tuple, but I wanted to avoid using that word due to the immutable nature of tuples.

I am aware of two easy ways to concatenate tuples in Python, but I am curious which options is faster / more efficient or if they both behave the same on the low level.

1) Create a new tuple and concatenate them using + operator:

oldTuple = (1, 2, 3)
value1 = 4
value2 = 5
result = oldTuple + (value1, value2)

2) Unpack the old tuple and construct a new one with the new items:

oldTuple = (1, 2, 3)
value1 = 4
value2 = 5
result = (*oldTuple, value1, value2)

Are both of these ways of tuple concatenation acceptable or is one of them better?

Is there a more efficient way to do this?

Would one become more / less efficient based on the length of the second tuple?

natiiix
  • 1,005
  • 1
  • 13
  • 21
  • Some answer there talks about efficiency, the second method being 10 times slower that the first. You can time them using `%timeit` – Sheldore Jun 14 '19 at 13:45
  • More similar question [here](https://stackoverflow.com/questions/53984406/efficient-way-to-add-elements-to-a-tuple) – Sheldore Jun 14 '19 at 13:47
  • @Sheldore Oh, thanks, I saw the first question, but I didn't notice any answer mentioning the second option. I'm sorry about that. I wasn't sure if the results would be consistent regardless of size, etc., which is why I asked. Didn't see the second question at all, but it doesn't mention the difference in efficiency. – natiiix Jun 14 '19 at 14:13

0 Answers0