python: append & extend 異同
阿新 • • 發佈:2019-02-14
經過試驗,總結出 python 中 append 和 extend 的異同點如下表:
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’:說明append、 extend只能作用於 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 argument、TypeError: extend() takes exactly one argument:說明append、 extend每次只能輸入單引數。