Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to add elements to a tuple

Tags:

python

tuples

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!

like image 691
Nagabhushan S N Avatar asked Dec 31 '18 06:12

Nagabhushan S N


1 Answers

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:]
like image 185
cs95 Avatar answered Oct 08 '22 10:10

cs95