Difference between append vs. extend list methods

2018-12-31 01:13发布

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

24条回答
浅入江南
2楼-- · 2018-12-31 01:28

Append a dictionary to another one:

>>>def foo():
    dic = {1:'a', 2:'b', 3:'c', 4:'a'}
    newdic = {5:'v', 1:'aa'}
    for i in dic.keys():
        if not newdic.has_key(dic[i]):
            newdic[i] = dic[i]
    print "Appended one:", newdic

>>>foo()
Appended one: {1: 'a', 2: 'b', 3: 'c', 4: 'a', 5: 'v'}
查看更多
余欢
3楼-- · 2018-12-31 01:28

The method "append" adds its parameter as a single element to the list, while "extend" gets a list and adds its content.

For example,

extend

    letters = ['a', 'b']
    letters.extend(['c', 'd'])
    print(letters) # ['a', 'b', 'c', 'd']

append

    letters.append(['e', 'f'])
    print(letters) # ['a', 'b', 'c', 'd', ['e', 'f']]
查看更多
不流泪的眼
4楼-- · 2018-12-31 01:34

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.

查看更多
裙下三千臣
5楼-- · 2018-12-31 01:35

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.

查看更多
几人难应
6楼-- · 2018-12-31 01:38

append() method will add the argument passed to it as a single element.

extend () will iterated over the arguments passed and extend the list by passing each elements iterated, basically it will add multiple elements not adding whole as one.

list1 = [1,2,3,4,5]
list2 = [6,7,8]

list1.append(list2)
print(list1)
#[1,2,3,4,5,[6,7,8]]

list1.extend(list2)
print(list1)
#[1,2,3,4,5,6,7,8]
查看更多
爱死公子算了
7楼-- · 2018-12-31 01:41

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]
查看更多
登录 后发表回答