这是一个重复的问题:
Python append() vs. + operator on lists, why do these give different results? 在Python中,列表操作中"+"和"append"之间的实际区别是什么?
Python append() vs. + operator on lists, why do these give different results? 在Python中,列表操作中"+"和"append"之间的实际区别是什么?
有两个主要的区别。第一个区别是+
更接近于extend
而非append
:
>>> a = [1, 2, 3]
>>> a + 4
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
a + 4
TypeError: can only concatenate list (not "int") to list
>>> a + [4]
[1, 2, 3, 4]
>>> a.append([4])
>>> a
[1, 2, 3, [4]]
>>> a.extend([4])
>>> a
[1, 2, 3, [4], 4]
另一个更显著的区别是这些方法会在原地进行操作:extend
实际上就像 +=
- 实际上,它与 +=
的行为完全相同,只是它可以接受任何可迭代对象,而 +=
只能接受另一个列表。
使用 list.append
直接修改列表 - 它的结果是 None
。使用 + 创建一个新的列表。
+
操作符可以创建一个新的列表,而不改变原始列表,你应该知道你是否打算改变原始列表。 - Azim>>> L1 = [1,2,3]
>>> L2 = [97,98,99]
>>>
>>> # Mutate L1 by appending more values:
>>> L1.append(4)
>>> L1
[1, 2, 3, 4]
>>>
>>> # Create a new list by adding L1 and L2 together
>>> L1 + L2
[1, 2, 3, 4, 97, 98, 99]
>>> # L1 and L2 are unchanged
>>> L1
[1, 2, 3, 4]
>>> L2
[97, 98, 99]
>>>
>>> # Mutate L2 by adding new values to it:
>>> L2 += [999]
>>> L2
[97, 98, 99, 999]
+
是一个二元运算符,它将两个操作数列表连接起来并生成一个新的列表。 append
是一个实例方法,它将单个元素附加到现有列表中。
P.S. 你是不是想用 extend
?
+
操作将数组元素添加到原始数组中。 array.append
操作将数组(或任何对象)插入到原始数组的末尾。
[1, 2, 3] + [4, 5, 6] // [1, 2, 3, 4, 5, 6]
b = [1, 2, 3]
b.append([4, 5, 6]) // [1, 2, 3, [4, 5, 6]]
+= can only take another list.
I think it can take tuples too or else how do explain being able to add to a list with+= 8,
- mj_codec