Python的list方法append和extend有什么区别?

问题:Python的list方法append和extend有什么区别?

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

What’s the difference between the list methods append() and extend()?


回答 0

append:在末尾追加对象。

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

给你: [1, 2, 3, [4, 5]]


extend:通过附加来自iterable的元素来扩展列表。

x = [1, 2, 3]
x.extend([4, 5])
print (x)

给你: [1, 2, 3, 4, 5]

append: Appends object at the end.

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

gives you: [1, 2, 3, [4, 5]]


extend: Extends list by appending elements from the iterable.

x = [1, 2, 3]
x.extend([4, 5])
print (x)

gives you: [1, 2, 3, 4, 5]


回答 1

append将元素添加到列表,并将extend第一个列表与另一个列表(或另一个可迭代的列表,不一定是列表)连接。

>>> li = ['a', 'b', 'mpilgrim', 'z', 'example']
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']

>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']

>>> li.append(["new", 2])
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]

>>> li.insert(2, "new")
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]

>>> li.extend(["two", "elements"])
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2], 'two', 'elements']

append adds an element to a list, and extend concatenates the first list with another list (or another iterable, not necessarily a list.)

>>> li = ['a', 'b', 'mpilgrim', 'z', 'example']
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']

>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']

>>> li.append(["new", 2])
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]

>>> li.insert(2, "new")
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]

>>> li.extend(["two", "elements"])
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2], 'two', 'elements']

回答 2

列表方法追加和扩展之间有什么区别?

  • append将其参数作为单个元素添加到列表的末尾。列表本身的长度将增加一。
  • extend遍历其参数,将每个元素添加到列表,扩展列表。无论迭代参数中有多少元素,列表的长度都会增加。

append

list.append方法将一个对象附加到列表的末尾。

my_list.append(object) 

无论对象是什么,无论是数字,字符串,另一个列表还是其他对象,它都将my_list作为单个条目添加到列表的末尾。

>>> my_list
['foo', 'bar']
>>> my_list.append('baz')
>>> my_list
['foo', 'bar', 'baz']

因此请记住,列表是一个对象。如果将另一个列表追加到列表中,则第一个列表将是列表末尾的单个对象(可能不是您想要的):

>>> another_list = [1, 2, 3]
>>> my_list.append(another_list)
>>> my_list
['foo', 'bar', 'baz', [1, 2, 3]]
                     #^^^^^^^^^--- single item at the end of the list.

extend

list.extend方法通过附加来自可迭代对象的元素来扩展列表:

my_list.extend(iterable)

因此,通过扩展,可迭代的每个元素都将附加到列表中。例如:

>>> my_list
['foo', 'bar']
>>> another_list = [1, 2, 3]
>>> my_list.extend(another_list)
>>> my_list
['foo', 'bar', 1, 2, 3]

请记住,字符串是可迭代的,因此,如果用字符串扩展列表,则在迭代字符串时将附加每个字符(可能不是您想要的):

>>> my_list.extend('baz')
>>> my_list
['foo', 'bar', 1, 2, 3, 'b', 'a', 'z']

运算符重载,__add__+)和__iadd__+=

这两个++=运营商的定义list。它们在语义上类似扩展。

my_list + another_list 在内存中创建第三个列表,因此您可以返回它的结果,但是它要求第二个可迭代的列表。

my_list += another_list就地修改列表(如我们所见,它就地运算符,并且列表是可变对象),因此不会创建新列表。它也像扩展一样工作,因为第二个可迭代对象可以是任何一种可迭代对象。

不要混淆- my_list = my_list + another_list不等于+=-它为您提供了分配给my_list的全新列表。

时间复杂度

追加具有恒定的时间复杂度 O(1)。

扩展具有时间复杂度O(k)。

遍历多次调用会append增加复杂性,使其等效于extend的复杂性,并且由于extend的迭代是在C中实现的,因此,如果您打算将可迭代对象的后续项追加到列表中,它将总是更快。

性能

您可能会想知道什么是性能更高的,因为append可以用来实现与extend相同的结果。以下功能执行相同的操作:

def append(alist, iterable):
    for item in iterable:
        alist.append(item)

def extend(alist, iterable):
    alist.extend(iterable)

因此,让我们为它们计时:

import timeit

>>> min(timeit.repeat(lambda: append([], "abcdefghijklmnopqrstuvwxyz")))
2.867846965789795
>>> min(timeit.repeat(lambda: extend([], "abcdefghijklmnopqrstuvwxyz")))
0.8060121536254883

在时间上发表评论

评论者说:

完美的答案,我只是错过了仅添加一个元素进行比较的时机

做语义上正确的事情。如果您想将所有元素附加到可迭代对象中,请使用extend。如果您仅添加一个元素,请使用append

好的,让我们创建一个实验来看看如何及时进行:

def append_one(a_list, element):
    a_list.append(element)

def extend_one(a_list, element):
    """creating a new list is semantically the most direct
    way to create an iterable to give to extend"""
    a_list.extend([element])

import timeit

而且我们看到,单单使用扩展创建一个可迭代的方法是(少量)浪费时间:

>>> min(timeit.repeat(lambda: append_one([], 0)))
0.2082819009956438
>>> min(timeit.repeat(lambda: extend_one([], 0)))
0.2397019260097295

我们从中了解到,extend只有一个元素要附加时,使用并没有任何好处。

同样,这些时间并不是那么重要。我只是向他们说明,在Python中做正确的语义就是正确的方法。

可以想象,您可以在两个可比较的操作上测试时序,并得到模棱两可或相反的结果。只要专注于做语义上正确的事情。

结论

我们看到,extend在语义上更清晰,而且它可以比运行速度非常快append当你打算在一个迭代的每个元素添加到列表中。

如果只有一个元素(不可迭代)添加到列表中,请使用append

What is the difference between the list methods append and extend?

  • append adds its argument as a single element to the end of a list. The length of the list itself will increase by one.
  • extend iterates over its argument adding each element to the list, extending the list. The length of the list will increase by however many elements were in the iterable argument.

append

The list.append method appends an object to the end of the list.

my_list.append(object) 

Whatever the object is, whether a number, a string, another list, or something else, it gets added onto the end of my_list as a single entry on the list.

>>> my_list
['foo', 'bar']
>>> my_list.append('baz')
>>> my_list
['foo', 'bar', 'baz']

So keep in mind that a list is an object. If you append another list onto a list, the first list will be a single object at the end of the list (which may not be what you want):

>>> another_list = [1, 2, 3]
>>> my_list.append(another_list)
>>> my_list
['foo', 'bar', 'baz', [1, 2, 3]]
                     #^^^^^^^^^--- single item at the end of the list.

extend

The list.extend method extends a list by appending elements from an iterable:

my_list.extend(iterable)

So with extend, each element of the iterable gets appended onto the list. For example:

>>> my_list
['foo', 'bar']
>>> another_list = [1, 2, 3]
>>> my_list.extend(another_list)
>>> my_list
['foo', 'bar', 1, 2, 3]

Keep in mind that a string is an iterable, so if you extend a list with a string, you’ll append each character as you iterate over the string (which may not be what you want):

>>> my_list.extend('baz')
>>> my_list
['foo', 'bar', 1, 2, 3, 'b', 'a', 'z']

Operator Overload, __add__ (+) and __iadd__ (+=)

Both + and += operators are defined for list. They are semantically similar to extend.

my_list + another_list creates a third list in memory, so you can return the result of it, but it requires that the second iterable be a list.

my_list += another_list modifies the list in-place (it is the in-place operator, and lists are mutable objects, as we’ve seen) so it does not create a new list. It also works like extend, in that the second iterable can be any kind of iterable.

Don’t get confused – my_list = my_list + another_list is not equivalent to += – it gives you a brand new list assigned to my_list.

Time Complexity

Append has constant time complexity, O(1).

Extend has time complexity, O(k).

Iterating through the multiple calls to append adds to the complexity, making it equivalent to that of extend, and since extend’s iteration is implemented in C, it will always be faster if you intend to append successive items from an iterable onto a list.

Performance

You may wonder what is more performant, since append can be used to achieve the same outcome as extend. The following functions do the same thing:

def append(alist, iterable):
    for item in iterable:
        alist.append(item)

def extend(alist, iterable):
    alist.extend(iterable)

So let’s time them:

import timeit

>>> min(timeit.repeat(lambda: append([], "abcdefghijklmnopqrstuvwxyz")))
2.867846965789795
>>> min(timeit.repeat(lambda: extend([], "abcdefghijklmnopqrstuvwxyz")))
0.8060121536254883

Addressing a comment on timings

A commenter said:

Perfect answer, I just miss the timing of comparing adding only one element

Do the semantically correct thing. If you want to append all elements in an iterable, use extend. If you’re just adding one element, use append.

Ok, so let’s create an experiment to see how this works out in time:

def append_one(a_list, element):
    a_list.append(element)

def extend_one(a_list, element):
    """creating a new list is semantically the most direct
    way to create an iterable to give to extend"""
    a_list.extend([element])

import timeit

And we see that going out of our way to create an iterable just to use extend is a (minor) waste of time:

>>> min(timeit.repeat(lambda: append_one([], 0)))
0.2082819009956438
>>> min(timeit.repeat(lambda: extend_one([], 0)))
0.2397019260097295

We learn from this that there’s nothing gained from using extend when we have only one element to append.

Also, these timings are not that important. I am just showing them to make the point that, in Python, doing the semantically correct thing is doing things the Right Way™.

It’s conceivable that you might test timings on two comparable operations and get an ambiguous or inverse result. Just focus on doing the semantically correct thing.

Conclusion

We see that extend is semantically clearer, and that it can run much faster than append, when you intend to append each element in an iterable to a list.

If you only have a single element (not in an iterable) to add to the list, use append.


回答 3

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

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

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

append appends a single element. extend appends a list of elements.

Note that if you pass a list to append, it still adds one element:

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

回答 4

追加与扩充

使用append,您可以附加一个元素来扩展列表:

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

如果要扩展多个元素,则应使用extend,因为您只能附加一个元素或一个元素列表:

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

这样您就可以获得一个嵌套列表

您可以像这样通过扩展来扩展单个元素

>>> a = [1,2]
>>> a.extend([3])
>>> a
[1,2,3]

或者,与追加不同的是,一次扩展更多元素而不将列表嵌套到原始列表中(这就是名称扩展的原因)

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

两种方法都添加一个元素

尽管添加和添加都比较简单,但是添加和扩展都可以在列表末尾添加一个元素。

追加1个元素

>>> x = [1,2]
>>> x.append(3)
>>> x
[1,2,3]

扩展一个元素

>>> x = [1,2]
>>> x.extend([3])
>>> x
[1,2,3]

添加更多元素…结果不同

如果对多个元素使用append,则必须将元素列表作为参数传递,您将获得NESTED列表!

>>> x = [1,2]
>>> x.append([3,4])
>>> x
[1,2,[3,4]]

相反,使用extend,您将一个列表作为参数传递,但是您将获得一个列表,其中包含未嵌套在旧元素中的新元素。

>>> z = [1,2] 
>>> z.extend([3,4])
>>> z
[1,2,3,4]

因此,使用更多元素,您将使用extend获得包含更多项目的列表。但是,追加列表不会在列表中添加更多元素,而是一个嵌套列表的元素,您可以在代码输出中清楚地看到。

Append vs Extend

With append you can append a single element that will extend the list:

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

If you want to extend more than one element you should use extend, because you can only append one elment or one list of element:

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

So that you get a nested list

Instead with extend, you can extend a single element like this

>>> a = [1,2]
>>> a.extend([3])
>>> a
[1,2,3]

Or, differently, from append, extend more elements in one time without nesting the list into the original one (that’s the reason of the name extend)

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

Adding one element with both methods

Both append and extend can add one element to the end of the list, though append is simpler.

append 1 element

>>> x = [1,2]
>>> x.append(3)
>>> x
[1,2,3]

extend one element

>>> x = [1,2]
>>> x.extend([3])
>>> x
[1,2,3]

Adding more elements… with different results

If you use append for more than one element, you have to pass a list of elements as arguments and you will obtain a NESTED list!

>>> x = [1,2]
>>> x.append([3,4])
>>> x
[1,2,[3,4]]

With extend, instead, you pass a list as an argument, but you will obtain a list with the new element that is not nested in the old one.

>>> z = [1,2] 
>>> z.extend([3,4])
>>> z
[1,2,3,4]

So, with more elements, you will use extend to get a list with more items. However, appending a list will not add more elements to the list, but one element that is a nested list as you can clearly see in the output of the code.


回答 5

以下两个片段在语义上是等效的:

for item in iterator:
    a_list.append(item)

a_list.extend(iterator)

当循环在C中实现时,后者可能会更快。

The following two snippets are semantically equivalent:

for item in iterator:
    a_list.append(item)

and

a_list.extend(iterator)

The latter may be faster as the loop is implemented in C.


回答 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

The append() method adds a single item to the end of the list.

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

The extend() method takes one argument, a list, and appends each of the items of the argument to the original list. (Lists are implemented as classes. “Creating” a list is really instantiating a class. As such, a list has methods that operate on it.)

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

From Dive Into Python.


回答 7

您可以使用“ +”返回扩展名,而不是就地扩展名。

l1=range(10)

l1+[11]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]

l2=range(10,1,-1)

l1+l2

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]

+=就地行为类似,但与append&略有不同extend。其中一个最大的不同+=,从appendextend是当它在功能范围时,看到这个博客帖子

You can use “+” for returning extend, instead of extending in place.

l1=range(10)

l1+[11]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]

l2=range(10,1,-1)

l1+l2

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]

Similarly += for in place behavior, but with slight differences from append & extend. One of the biggest differences of += from append and extend is when it is used in function scopes, see this blog post.


回答 8

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(object) – Updates the list by adding an object to the list.

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) – Essentially concatenates two lists.

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]

回答 9

extend()可以与迭代器参数一起使用。这是一个例子。您希望通过以下方式从列表列表中列出一个列表:

list2d = [[1,2,3],[4,5,6], [7], [8,9]]

你要

>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]

您可能itertools.chain.from_iterable()会这样做。该方法的输出是一个迭代器。它的实现等效于

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

回到我们的例子,我们可以做

import itertools
list2d = [[1,2,3],[4,5,6], [7], [8,9]]
merged = list(itertools.chain.from_iterable(list2d))

并获得通缉名单。

以下是等效extend()用于迭代器参数的方法:

merged = []
merged.extend(itertools.chain.from_iterable(list2d))
print(merged)
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]

extend() can be used with an iterator argument. Here is an example. You wish to make a list out of a list of lists this way:

From

list2d = [[1,2,3],[4,5,6], [7], [8,9]]

you want

>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]

You may use itertools.chain.from_iterable() to do so. This method’s output is an iterator. Its implementation is equivalent to

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

Back to our example, we can do

import itertools
list2d = [[1,2,3],[4,5,6], [7], [8,9]]
merged = list(itertools.chain.from_iterable(list2d))

and get the wanted list.

Here is how equivalently extend() can be used with an iterator argument:

merged = []
merged.extend(itertools.chain.from_iterable(list2d))
print(merged)
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]

回答 10

这等效于appendextend使用+运算符:

>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> x = x + [4,5,6] # Extend
>>> x
[1, 2, 3, 4, 5, 6]
>>> x = x + [[7,8]] # Append
>>> x
[1, 2, 3, 4, 5, 6, [7, 8]]

This is the equivalent of append and extend using the + operator:

>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> x = x + [4,5,6] # Extend
>>> x
[1, 2, 3, 4, 5, 6]
>>> x = x + [[7,8]] # Append
>>> x
[1, 2, 3, 4, 5, 6, [7, 8]]

回答 11

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(): It is basically used in Python to add one element.

Example 1:

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

Example 2:

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

extend(): Where extend(), is used to merge two lists or insert multiple elements in one list.

Example 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]

Example 2:

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

回答 12

已经暗示但未解释的一个有趣的观点是,扩展比添加快。对于任何在内部具有append的循环,都应考虑将其替换为list.extend(processed_elements)。

请记住,添加新元素可能会导致整个列表重新定位到内存中的更好位置。如果由于一次添加1个元素而多次执行此操作,则总体性能会受到影响。在这种意义上,list.extend类似于“” .join(stringlist)。

An interesting point that has been hinted, but not explained, is that extend is faster than append. For any loop that has append inside should be considered to be replaced by list.extend(processed_elements).

Bear in mind that apprending new elements might result in the realloaction of the whole list to a better location in memory. If this is done several times because we are appending 1 element at a time, overall performance suffers. In this sense, list.extend is analogous to “”.join(stringlist).


回答 13

Append一次添加全部数据。整个数据将被添加到新创建的索引中。另一方面,extend顾名思义,扩展了当前数组。

例如

list1 = [123, 456, 678]
list2 = [111, 222]

随着append我们得到:

result = [123, 456, 678, [111, 222]]

extend我们得到:

result = [123, 456, 678, 111, 222]

Append adds the entire data at once. The whole data will be added to the newly created index. On the other hand, extend, as it name suggests, extends the current array.

For example

list1 = [123, 456, 678]
list2 = [111, 222]

With append we get:

result = [123, 456, 678, [111, 222]]

While on extend we get:

result = [123, 456, 678, 111, 222]

回答 14

一本英语词典定义的话append,并extend为:

append:在书面文档的末尾添加(某些内容)。
扩大:扩大。放大或扩大


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

1)之间的区别appendextend

append

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

extend

  • 接受任何iterable作为其参数,并使列表更大
  • 结果列表始终是一维列表(即无嵌套),由于apply的结果,列表中可能包含异类元素(例如,字符,整数,浮点数)list(iterable)

2)之间的相似性appendextend

  • 两者都只是一个论点。
  • 两者都就地修改列表。
  • 结果,两个都返回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)

An English dictionary defines the words append and extend as:

append: add (something) to the end of a written document.
extend: make larger. Enlarge or expand


With that knowledge, now let’s understand

1) The difference between append and extend

append:

  • Appends any Python object as-is to the end of the list (i.e. as a the last element in the list).
  • The resulting list may be nested and contain heterogeneous elements (i.e. list, string, tuple, dictionary, set, etc.)

extend:

  • Accepts any iterable as its argument and makes the list larger.
  • The resulting list is always one-dimensional list (i.e. no nesting) and it may contain heterogeneous elements in it (e.g. characters, integers, float) as a result of applying list(iterable).

2) Similarity between append and extend

  • Both take exactly one argument.
  • Both modify the list in-place.
  • As a result, both returns None.

Example

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)

回答 15

我希望我可以对这个问题做出有益的补充。例如Info,如果您的列表存储了一个特定类型的对象,则这种情况extend不适用于该方法:在for循环中,Info每次生成一个对象并extend用于将其存储到列表中时,它将失败。异常如下所示:

TypeError:“ Info”对象不可迭代

但是,如果使用该append方法,则结果可以。因为每次使用该extend方法时,它将始终将其视为列表或任何其他集合类型,因此需要对其进行迭代,并将其放置在上一个列表之后。显然,不能迭代特定的对象。

I hope I can make a useful supplement to this question. If your list stores a specific type object, for example Info, here is a situation that extend method is not suitable: In a for loop and and generating an Info object every time and using extend to store it into your list, it will fail. The exception is like below:

TypeError: ‘Info’ object is not iterable

But if you use the append method, the result is OK. Because every time using the extend method, it will always treat it as a list or any other collection type, iterate it, and place it after the previous list. A specific object can not be iterated, obviously.


回答 16

直观区分它们

l1 = ['a', 'b', 'c']
l2 = ['d', 'e', 'f']
l1.append(l2)
l1
['a', 'b', 'c', ['d', 'e', 'f']]

就像l1在她体内复制一个身体(嵌套)一样。

# Reset l1 = ['a', 'b', 'c']
l1.extend(l2)
l1
['a', 'b', 'c', 'd', 'e', 'f']

就像两个分开的人结婚并组建了一个家庭。

此外,我还列出了所有列表方法的详尽清单供您参考。

list_methods = {'Add': {'extend', 'append', 'insert'},
                'Remove': {'pop', 'remove', 'clear'}
                'Sort': {'reverse', 'sort'},
                'Search': {'count', 'index'},
                'Copy': {'copy'},
                }

To distinguish them intuitively

l1 = ['a', 'b', 'c']
l2 = ['d', 'e', 'f']
l1.append(l2)
l1
['a', 'b', 'c', ['d', 'e', 'f']]

It’s like l1 reproduce a body inside her body(nested).

# Reset l1 = ['a', 'b', 'c']
l1.extend(l2)
l1
['a', 'b', 'c', 'd', 'e', 'f']

It’s like that two separated individuals get married and construct an united family.

Besides I make an exhaustive cheatsheet of all list’s methods for your reference.

list_methods = {'Add': {'extend', 'append', 'insert'},
                'Remove': {'pop', 'remove', 'clear'}
                'Sort': {'reverse', 'sort'},
                'Search': {'count', 'index'},
                'Copy': {'copy'},
                }

回答 17

extend(L)通过在给定列表中追加所有项目来扩展列表L

>>> a
[1, 2, 3]
a.extend([4])  #is eqivalent of a[len(a):] = [4]
>>> a
[1, 2, 3, 4]
a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a[len(a):] = [4]
>>> a
[1, 2, 3, 4]

extend(L) extends the list by appending all the items in the given list L.

>>> a
[1, 2, 3]
a.extend([4])  #is eqivalent of a[len(a):] = [4]
>>> a
[1, 2, 3, 4]
a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a[len(a):] = [4]
>>> a
[1, 2, 3, 4]

回答 18

append列表仅将一项 “扩展”(就地),即传递的单个对象(作为参数)。

extend“扩展”的名单(到位)尽可能多的项目对象传递(作为参数)包含的内容。

这可能会使str对象有些混乱。

  1. 如果您将字符串作为参数传递: append将在末尾添加单个字符串项,但 extend将添加与该字符串的长度一样多的“单个”“ str”项。
  2. 如果您将字符串列表作为参数传递:: append仍将在末尾添加单个“列表”项, extend并将添加与所传递列表的长度一样多的“列表”项。
def append_o(a_list, element):
    a_list.append(element)
    print('append:', end = ' ')
    for item in a_list:
        print(item, end = ',')
    print()

def extend_o(a_list, element):
    a_list.extend(element)
    print('extend:', end = ' ')
    for item in a_list:
        print(item, end = ',')
    print()
append_o(['ab'],'cd')

extend_o(['ab'],'cd')
append_o(['ab'],['cd', 'ef'])
extend_o(['ab'],['cd', 'ef'])
append_o(['ab'],['cd'])
extend_o(['ab'],['cd'])

生成:

append: ab,cd,
extend: ab,c,d,
append: ab,['cd', 'ef'],
extend: ab,cd,ef,
append: ab,['cd'],
extend: ab,cd,

append “extends” the list (in place) by only one item, the single object passed (as argument).

extend “extends” the list (in place) by as many items as the object passed (as argument) contains.

This may be slightly confusing for str objects.

  1. If you pass a string as argument: append will add a single string item at the end but extend will add as many “single” ‘str’ items as the length of that string.
  2. If you pass a list of strings as argument: append will still add a single ‘list’ item at the end and extend will add as many ‘list’ items as the length of the passed list.
def append_o(a_list, element):
    a_list.append(element)
    print('append:', end = ' ')
    for item in a_list:
        print(item, end = ',')
    print()

def extend_o(a_list, element):
    a_list.extend(element)
    print('extend:', end = ' ')
    for item in a_list:
        print(item, end = ',')
    print()
append_o(['ab'],'cd')

extend_o(['ab'],'cd')
append_o(['ab'],['cd', 'ef'])
extend_o(['ab'],['cd', 'ef'])
append_o(['ab'],['cd'])
extend_o(['ab'],['cd'])

produces:

append: ab,cd,
extend: ab,c,d,
append: ab,['cd', 'ef'],
extend: ab,cd,ef,
append: ab,['cd'],
extend: ab,cd,

回答 19

追加和扩展是python中的可扩展性机制之一。

追加:将元素添加到列表的末尾。

my_list = [1,2,3,4]

要向列表中添加新元素,我们可以通过以下方式使用append方法。

my_list.append(5)

将要添加新元素的默认位置始终位于(length + 1)位置。

插入:使用插入方法来克服附加的限制。使用insert,我们可以显式定义要在其中插入新元素的确切位置。

insert(index,object)的方法描述符。它有两个参数,第一个是我们要插入元素的索引,第二个是元素本身。

Example: my_list = [1,2,3,4]
my_list[4, 'a']
my_list
[1,2,3,4,'a']

扩展:当我们要将两个或多个列表合并为一个列表时,这非常有用。如果不扩展,如果我们要连接两个列表,则生成的对象将包含一个列表列表。

a = [1,2]
b = [3]
a.append(b)
print (a)
[1,2,[3]]

如果尝试访问位置2的元素,则会得到一个列表([3]),而不是元素。要加入两个列表,我们必须使用append。

a = [1,2]
b = [3]
a.extend(b)
print (a)
[1,2,3]

加入多个列表

a = [1]
b = [2]
c = [3]
a.extend(b+c)
print (a)
[1,2,3]

Append and extend are one of the extensibility mechanisms in python.

Append: Adds an element to the end of the list.

my_list = [1,2,3,4]

To add a new element to the list, we can use append method in the following way.

my_list.append(5)

The default location that the new element will be added is always in the (length+1) position.

Insert: The insert method was used to overcome the limitations of append. With insert, we can explicitly define the exact position we want our new element to be inserted at.

Method descriptor of insert(index, object). It takes two arguments, first being the index we want to insert our element and second the element itself.

Example: my_list = [1,2,3,4]
my_list[4, 'a']
my_list
[1,2,3,4,'a']

Extend: This is very useful when we want to join two or more lists into a single list. Without extend, if we want to join two lists, the resulting object will contain a list of lists.

a = [1,2]
b = [3]
a.append(b)
print (a)
[1,2,[3]]

If we try to access the element at pos 2, we get a list ([3]), instead of the element. To join two lists, we’ll have to use append.

a = [1,2]
b = [3]
a.extend(b)
print (a)
[1,2,3]

To join multiple lists

a = [1]
b = [2]
c = [3]
a.extend(b+c)
print (a)
[1,2,3]