当前位置:主页 > 软件编程 > Python代码 >

Python中extend和append的区别讲解

时间:2021-05-14 10:37:22 | 栏目:Python代码 | 点击:

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)

总结

您可能感兴趣的文章:

相关文章