21

我正在阅读Dive into Python 3,在列表部分,作者指出您可以使用“+”运算符连接列表或调用 extend() 方法。这些只是两种不同的操作方式吗?有什么理由我应该使用其中一个吗?

>>> a_list = a_list + [2.0, 3]
>>> a_list.extend([2.0, 3])  
4

1 回答 1

36

a_list.extend(b_list) modifies a_list in place. a_list = a_list + b_list creates a new list, then saves it to the name a_list. Note that a_list += b_list should be exactly the same as the extend version.

Using extend or += is probably slightly faster, since it doesn't need to create a new object, but if there's another reference to a_list around, it's value will be changed too (which may or may not be desirable).

于 2013-01-13T06:02:53.583 回答