python: append & extend 异同

来源:互联网 发布:快刀抢票软件 编辑:程序博客网 时间:2024/05/17 02:15

  经过试验,总结出 python 中 appendextend 的异同点如下表:

Func Same Point Difference append 只能作用于 list 型数据,每次只能输入 参数 只能以 单元素 的形式被 添加到 list 尾部,list层级数加1 extend 同上 只能以 list 的形式被 连接到 list 尾部,不改变list层级数



  代码示例0:

list = ('Hello', 1, '@')list
('Hello', 1, '@')


 list.append('#')
Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'tuple' object has no attribute 'append'


list.extend('#')
Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'tuple' object has no attribute 'extend'

  AttributeError: ‘tuple’ object has no attribute ‘append’、 ‘extend’:说明appendextend只能作用于 list 型数据。


  代码示例1:

list = ['Hello', 1, '@']list.append(2)list
['Hello', 1, '@', 2, 3]


list = ['Hello', 1, '@', 2]list.append((3, 4))list
['Hello', 1, '@', 2, (3, 4)]


list.append([3, 4])list
['Hello', 1, '@', 2, (3, 4), [3, 4]]


list.append(3, 4)
Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: append() takes exactly one argument (2 given)


list.extend([5, 6])list
['Hello', 1, '@', 2, (3, 4), [3, 4], 5, 6]


list.extend((5, 6))list
['Hello', 1, '@', 2, (3, 4), [3, 4], 5, 6, 5, 6]


list.extend(5, 6)
Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: extend() takes exactly one argument (2 given)


  TypeError: append() takes exactly one argumentTypeError: extend() takes exactly one argument:说明appendextend每次只能输入单参数。



原创粉丝点击