将元素附加到列表的操作更快

时间:2013-08-04 09:13:12

标签: python python-2.7

我需要在列表中添加一个/多个元素,我有两个选择:

mylist=mylist+newlist(elemet)

mylist.append(ele);

哪一个会更快?

1 个答案:

答案 0 :(得分:1)

mylist.append(ele)会更快。这在Python Docs中有记载。

从文档引用 -

The method append() shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent to result = result + [a], but more efficient.

myList = myList + something必须创建一个新列表并重新分配。

比较timeit结果 -

>>> timeit('myList = myList + ["a"]', 'myList = []', number = 50000)
11.35058911138415
>>> timeit('myList.append("a")', 'myList = []', number = 50000)
0.010776052286637139