列表方法append()和extend()之间有什么区别?


当前回答

append(object)通过将对象添加到列表来更新列表。

x = [20]
# List passed to the append(object) method is treated as a single object.
x.append([21, 22, 23])
# Hence the resultant list length will be 2
print(x)
--> [20, [21, 22, 23]]

extend(list)本质上连接两个列表。

x = [20]
# The parameter passed to extend(list) method is treated as a list.
# Eventually it is two lists being concatenated.
x.extend([21, 22, 23])
# Here the resultant list's length is 4
print(x)
--> [20, 21, 22, 23]

其他回答

append():它基本上在Python中用于添加一个元素。

示例1:

>> a = [1, 2, 3, 4]
>> a.append(5)
>> print(a)
>> a = [1, 2, 3, 4, 5]

示例2:

>> a = [1, 2, 3, 4]
>> a.append([5, 6])
>> print(a)
>> a = [1, 2, 3, 4, [5, 6]]

extend():其中extend(()用于合并两个列表或在一个列表中插入多个元素。

示例1:

>> a = [1, 2, 3, 4]
>> b = [5, 6, 7, 8]
>> a.extend(b)
>> print(a)
>> a = [1, 2, 3, 4, 5, 6, 7, 8]

示例2:

>> a = [1, 2, 3, 4]
>> a.extend([5, 6])
>> print(a)
>> a = [1, 2, 3, 4, 5, 6]

append()方法将单个项添加到列表末尾。

x = [1, 2, 3]
x.append([4, 5])
x.append('abc')
print(x)
# gives you
[1, 2, 3, [4, 5], 'abc']

extend()方法接受一个参数,一个列表,并将该参数的每个项附加到原始列表中。(列表被实现为类。“创建”列表实际上是实例化一个类。因此,列表具有对其进行操作的方法。)

x = [1, 2, 3]
x.extend([4, 5])
x.extend('abc')
print(x)
# gives you
[1, 2, 3, 4, 5, 'a', 'b', 'c']

从潜入Python。

append附加一个元素。extend附加元素列表。

请注意,如果您传递一个列表进行追加,它仍然会添加一个元素:

>>> a = [1, 2, 3]
>>> a.append([4, 5, 6])
>>> a
[1, 2, 3, [4, 5, 6]]

append将元素添加到列表中。extend将第一个列表与另一个列表/可迭代列表连接起来。

>>> xs = ['A', 'B']
>>> xs
['A', 'B']

>>> xs.append("D")
>>> xs
['A', 'B', 'D']

>>> xs.append(["E", "F"])
>>> xs
['A', 'B', 'D', ['E', 'F']]

>>> xs.insert(2, "C")
>>> xs
['A', 'B', 'C', 'D', ['E', 'F']]

>>> xs.extend(["G", "H"])
>>> xs
['A', 'B', 'C', 'D', ['E', 'F'], 'G', 'H']

英语词典将单词append和extend定义为:

追加:在书面文档的末尾添加(某物)。扩展:放大。放大或展开


有了这些知识,现在让我们了解

1) append和extend之间的区别

附加:

将任何Python对象原样追加到列表末尾(即列表中的最后一个元素)。结果列表可以是嵌套的,并且包含异构元素(即列表、字符串、元组、字典、集合等)

扩展:

接受任何可迭代的作为其参数,并使列表更大。结果列表始终是一维列表(即无嵌套),并且由于应用列表(可迭代),它可能包含异类元素(例如字符、整数、浮点)。

2) 追加和扩展之间的相似性

两者都只接受一个论点。两者都会就地修改列表。结果,两者都返回None。


实例

lis = [1, 2, 3]

# 'extend' is equivalent to this
lis = lis + list(iterable)

# 'append' simply appends its argument as the last element to the list
# as long as the argument is a valid Python object
list.append(object)