Recently, when reading the source code of Scrapy, I saw the use of the list method append and extend. Look at the junior, still a little confused. Then look for some information to distinguish it.
The answer in StackOverflow is this:
Append: Append objects at tail (appends object at end)
C:\users\sniper.geek>python2
Python 2.7.9 (default, Dec, 12:28:03) [MSC v.1500-bit (AMD64)] on win
32
Type "Help", "copyright", "credits" or "license" For more information.
>>> x =[1,2,3]
>>> x.append ([4,5])
Print x
[1, 2, 3, [4, 5]]
>>>
For append, is it possible to append only one element? Try:
C:\users\sniper.geek>python2
Python 2.7.9 (default, Dec, 12:28:03) [MSC v.1500-bit (AMD64)] on win
32
Type "Help", "copyright", "credits" or "license" For more information.
>>> x=[1,2,3]
>>> X.append (5)
Print x
[1, 2, 3, 5]
>>>
Is it possible to append a single tuple? Keep trying:
C:\users\sniper.geek>python2
Python 2.7.9 (default, Dec, 12:28:03) [MSC v.1500-bit (AMD64)] on win
32
Type "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)]
>>>
In conclusion, append can append a list, append a tuple, or append a separate element.
Extend: extending a sequence by appending elements from an iterator (extends list by appending elements from the iterable)
C:\users\sniper.geek>python2
Python 2.7.9 (default, Dec, 12:28:03) [MSC v.1500-bit (AMD64)] on win
32
Type "Help", "copyright", "credits" or "license" For more information.
>>> x=[1,2,3]
>>> x.extend ([4,5])
Print x
[1, 2, 3, 4, 5]
>>>
So, can the extend parameter be a list or a tuple? Give it a try:
C:\users\sniper.geek>python2
Python 2.7.9 (default, Dec, 12:28:03) [MSC v.1500-bit (AMD64)] on win
32
Type "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]
>>>
In conclusion, the parameters of extend can be either a list or a tuple, except for a single element.
Summary:
- Both append and extend can only receive one parameter
- The Append parameter type is arbitrary, as shown above for a single element, a list or even a tuple is OK
- The parameters of the extend can be either a single element or a list with an iterator property, a tuple
- Append is to append the object as a whole to the list, extend is to add a list or tuple elements to the list, that is, append append a list or a tuple, the last element itself is a list or a tuple, When extend expands a list or tuple, the elements in the list are added one by one, and the last is a variable-length list.
Append and extend in the Python list