Python - extend vs append on a list

649阅读 0评论2011-10-04 大方无隅
分类:Python/Ruby

In Python, you can extend a list and you can append to it as well. 

What's the difference? If you append a list to another list, you add the new list as a single extra list to the original, thus makingthe original list just one longer with an item that is itself a list. But if you extend a list with another list, you add each element of the new list onto the original. Here's an example to show you what I mean:

>>> first = [10,20,30]
>>> second = [40,50,60]
>>> first.append([70,80,90])
>>> second.extend([100,110,120])
>>> first
[10, 20, 30, [70, 80, 90]]
>>> second
[40, 50, 60, 100, 110, 120]
>>> 

append(x) 追加到链尾

extend(L) 追加一个列表,等价于+=

从代码中可以看出:append追加的是一个值,extend追加的是一个数组(列表)

上一篇:python分片
下一篇:Python - extend vs append on a list