在Python中,".append()"和"+=[]"之间有什么区别?

147

什么是以下代码片段之间的区别:

some_list1 = []
some_list1.append("something")

以及

some_list2 = []
some_list2 += ["something"]

3
如果只是针对单个项目,您可能想使用“扩展(extend)”而不是“追加(append)”。 - hasen
2
对于更有趣的 += vs extend 情况,请参考:https://dev59.com/inA65IYBdhLWcg3wvxaE - Ciro Santilli OurBigBook.com
+=append的区别 https://dev59.com/w3VC5IYBdhLWcg3wjx_u - Semnodime
13个回答

1

从今天和Python 3.6开始,@Constantine提供的结果不再相同。

Python 3.6.10 |Anaconda, Inc.| (default, May  8 2020, 02:54:21) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.0447923709944007
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.04335783299757168

看起来现在append+=的性能相等,而编译差异并没有改变:

>>> import dis
>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec'))
  1           0 BUILD_LIST               0
              2 STORE_NAME               0 (s)
              4 LOAD_NAME                0 (s)
              6 LOAD_ATTR                1 (append)
              8 LOAD_CONST               0 ('spam')
             10 CALL_FUNCTION            1
             12 POP_TOP
             14 LOAD_CONST               1 (None)
             16 RETURN_VALUE
>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec'))
  1           0 BUILD_LIST               0
              2 STORE_NAME               0 (s)
              4 LOAD_NAME                0 (s)
              6 LOAD_CONST               0 ('spam')
              8 BUILD_LIST               1
             10 INPLACE_ADD
             12 STORE_NAME               0 (s)
             14 LOAD_CONST               1 (None)
             16 RETURN_VALUE

0

append() 方法将单个项目添加到现有列表中

some_list1 = []
some_list1.append("something")

所以这里的some_list1将被修改。

更新:

而使用+来组合现有列表中(多个元素)的元素与extend类似(由Flux更正)。

some_list2 = []
some_list2 += ["something"]

所以这里 some_list2 和 ["something"] 是被合并的两个列表。


1
这是错误的。+= 不会返回一个新列表。编程 FAQ 中说道:"... 对于列表,__iadd__ 等同于在列表上调用 extend 并返回该列表。这就是为什么我们说对于列表,+=list.extend 的 "简写"。" 您还可以在 CPython 源代码中自行查看:https://github.com/python/cpython/blob/v3.8.2/Objects/listobject.c#L1000-L1011 - Flux

0

让我们先举个例子

list1=[1,2,3,4]
list2=list1     (that means they points to same object)

if we do 
list1=list1+[5]    it will create a new object of list
print(list1)       output [1,2,3,4,5] 
print(list2)       output [1,2,3,4]

but if we append  then 
list1.append(5)     no new object of list created
print(list1)       output [1,2,3,4,5] 
print(list2)       output [1,2,3,4,5]

extend(list) also do the same work as append it just append a list instead of a 
single variable 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接