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!
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:]
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