Efficient way to add elements to a tuple

人盡茶涼 提交于 2019-12-10 20:42:59

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/53984406/efficient-way-to-add-elements-to-a-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!