最近,在閱讀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