List operations: Verbose + error-prone
Suppose there are two lists:
List1 = [A]
list2 = [' A ', ' B ', ' C '] list of operations:
1.list.append ()
Append only accepts one parameter
Append can only add elements at the end of the list and cannot select locations to add elements.
The following actions can be seen
>>> List1 = [+]
>>> list1.append (4)
>>> List1
[1, 2, 3, 4]
>>> list2 = [' A ', ' B ', ' C ']
>>> List2.append (d)//Add string to "
Traceback (most recent):
File "<stdin>", line 1, in <module>
nameerror:name ' d ' is not defined
>>> list2.append (' d ')
>>> List2
[' A ', ' B ', ' C ', ' d ']
2.list.extend ()
The Extend () method takes a list as an argument and adds each element of the parameter to the end of the original list.
If you add elements with extend (), you need to have the same type of elements as the original list, not very useful, if you need to add elements, use append better.
>>> list1.extend (list2)
>>> List1
[1, 2, 3, 4, ' A ', ' B ', ' C ', ' d ']
>>> list2 = [' A ', ' B ', ' C ']
>>> List1 = [+]
>>> list1.extend (' a ')
>>> List1
[1, 2, 3, ' a ']
>>> list2.extend (1)//Cannot add a number, the number is int
Traceback (most recent):
File "<stdin>", line 1, in <module>
TypeError: ' int ' object is not iterable
>>> list2.extend (' 1 ')//can add a string
>>> List2
[' A ', ' B ', ' C ', ' 1 ']
>>> list2.extend (int (1))
Traceback (most recent):
File "<stdin>", line 1, in <module>
TypeError: ' int ' object is not iterable
>>> list2 = [' A ', ' B ', ' C ']
>>> list2.append (1)
>>> List2
[' A ', ' B ', ' C ', 1]
3.list.insert ()
Insert () accepts two parameters, insert (insert position, insert Element) the insertion position starts at 0, and the inserted element precedes the first. Insert (I,X) I starting from 0, element x is inserted in front of I.
>>> num = [0,1,2,3]
>>> num.insert (0, ' a ')//insert as No. 0 element, starting from 0
>>> num
[' A ', 0, 1, 2, 3]//insert in front of the No. 0 element
Operation of the python--list