python列表中append和extend的区别

append和extend是list列表常见的两种扩充方法,两者看起来相似,但有很大区别,具体分析如下:

list.append(object)向列表种添加一个对象

list.extend(sequence)把一个序列的内容添加到列表中

这样说还是不太清楚,举个例子就清楚了

>>> #创建一个列表a
>>> a=[1,2,3,4]
>>> #利用append向a中加入数字5
>>> a.append(5)
>>> print(a)
[1, 2, 3, 4, 5]
>>> #向a中添加6,7,8
>>> a.append
<built-in method append of list object at 0x00000240A014FBC8>
>>> a.append(6,7,8)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    a.append(6,7,8)
TypeError: append() takes exactly one argument (3 given)
>>> #出现错误
>>> b=[6,7,8]
>>> a.append(b)
>>> print(b)
[6, 7, 8]
>>> print(a)
[1, 2, 3, 4, 5, [6, 7, 8]]
>>> #将b以列表形式添加进去了,还是不行,我们试试extend
>>> a.extend(b)
>>> print(a)
[1, 2, 3, 4, 5, [6, 7, 8], 6, 7, 8]
>>> 


猜你喜欢

转载自blog.csdn.net/qq_29023939/article/details/80840450