10

I want to add elements to a tuple. I found 2 ways to do it. This and this answers say add two tuples. It will create a new tuple

a = (1,2,3)
b = a + (5,)

Where as this says, convert the tuple to list, add the element and then convert it back to tuple

a = (1,2,3)
tmp = list(a)
tmp.insert(3, 'foobar')
b = tuple(tmp)

Which among these two is efficient in terms of memory and performance?
Also, suppose I want to insert an element in the middle of a tuple, is that possible using the first method?
Thanks!

Nagabhushan S N
  • 6,407
  • 8
  • 44
  • 87
  • 2
    Try to run `timeit` on the methods you mentioned to find out. see e.g. https://www.pythoncentral.io/time-a-python-function/ – Joe Dec 31 '18 at 06:50
  • 1
    The simple answer is: you can not add an item to a tuple. Tuples are immutable. You can on the other hand create a new tuple with that item. But you might want to use a list in the first place. – Klaus D. Dec 31 '18 at 07:04

1 Answers1

17

If you are only adding a single element, use

a += (5, )

Or,

a = (*a, 5)

Tuples are immutable, so adding an element will mean you will need to create a new tuple object. I would not recommend casting to a list unless you are going to add many elements in a loop, or such.

a_list = list(a)
for elem in iterable:
    result = process(elem)
    a_list.append(result)

a = tuple(a_list)

If you want to insert an element in the middle, you can use:

m = len(a) // 2
a = (*a[:m], 5, *a[m:])

Or,

a = a[:m] + (5, ) + a[m:]
cs95
  • 379,657
  • 97
  • 704
  • 746