网络编程
位置:首页>> 网络编程>> Python编程>> Python中extend和append的区别讲解

Python中extend和append的区别讲解

作者:youzhouliu  发布时间:2021-03-28 04:20:37 

标签:python,extend,append

append() 方法向列表的尾部添加一个新的元素。只接受一个参数。


>>> num = [1,2]
>>> num.append(3)
>>> num
[1, 2, 3]
>>> num.append('a')
>>> num
[1, 2, 3, 'a']
>>> num.append(6,7)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
 num.append(6,7)
TypeError: append() takes exactly one argument (2 given)
>>> num.append([6])
>>> num
[1, 2, 3, 'a', [6]]
>>> num.append({'a'})
>>> num
[1, 2, 3, 'a', [6], set(['a'])]

extend()方法只接受一个列表作为参数,并将该参数的每个元素都添加到原有的列表中。也是只接受一个参数。


>>> num=[1,2]
>>> num.extend([5])
>>> num
[1, 2, 5]
>>> num.extend(['b'])
>>> num
[1, 2, 5, 'b']
>>> num.extend(6,7)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
 num.extend(6,7)
TypeError: extend() takes exactly one argument (2 given)

来源:https://blog.csdn.net/youzhouliu/article/details/52698808

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com