最近,在阅读Scrapy的源码的时候,看到有关list方法append和extend的使用。初一看,仍是有些迷糊的。那就好好找点资料来辨析一下吧。python
stackoverflow中的回答是这样的:app
append:在尾部追加对象(Appends object at end)spa
C:\Users\sniper.geek>python2Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> x =[1,2,3]>>> x.append([4,5])>>> print x
[1, 2, 3, [4, 5]]>>>
对于append,是否能够只追加一个元素呢?试试看:orm
C:\Users\sniper.geek>python2Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> x=[1,2,3]>>> x.append(5)>>> print x
[1, 2, 3, 5]>>>
那是否能够追加一个元组呢?继续试试:对象
C:\Users\sniper.geek>python2Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> x=[1,2,3]>>> x.append(5)>>> print x
[1, 2, 3, 5]>>> x.append((6,7,8))>>> print x
[1, 2, 3, 5, (6, 7, 8)]>>>
综上可知,append能够追加一个list,还能够追加一个元组,也能够追加一个单独的元素。ip
extend:经过从迭代器中追加元素来扩展序列(extends list by appending elements from the iterable)element
C:\Users\sniper.geek>python2Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> x=[1,2,3]>>> x.extend([4,5])>>> print x
[1, 2, 3, 4, 5]>>>
那么,extend的参数是否能够为list或者元组呢?试一试:源码
C:\Users\sniper.geek>python2Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> x=[1,2,3]>>> x.extend([4,5,6])>>> print x
[1, 2, 3, 4, 5, 6]>>> x.extend((8,9,10))>>> print x
[1, 2, 3, 4, 5, 6, 8, 9, 10]>>>
综上可知:extend的参数除了为单个元素,也能够为list或者元组。it
总结: io