python基礎之append和extend的區別
阿新 • • 發佈:2018-12-09
1.append
a = [1,2,3]
b=[1,2]
a.append(b)
-------------------------------------------------
a
Out[60]: [1, 2, 3, [1, 2]]
將b作為整個元素append進去。
2.extend
a = [1,2,3]
b=[1,2]
a.extend(b)
-----------------------------------------------
a
Out[66]: [1, 2, 3, 1, 2]
將列表b中的元素分別append進去。
當內容為數值時,只能用append。
a = [1,2,3] a.append(3) -------------------------------------------- a Out[77]: [1, 2, 3, 3] -------------------------------------------- a.extend(3) Traceback (most recent call last): File "C:\local\Anaconda3-4.1.1-Windows-x86_64\lib\site-packages\IPython\core\interactiveshell.py", line 2885, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-78-0218884a1728>", line 1, in <module> a.extend(3) TypeError: 'int' object is not iterable ------------------------------------------- a.extend([3]) ------------------------------------------- a Out[80]: [1, 2, 3, 3, 3]