您的位置:首页 > 编程语言 > Python开发

Python中extend和append的区别讲解

2019-01-24 12:28 1121 查看

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)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: