I. Several ways to add elements to the list in Python
A list is a commonly used data type in Python, an ordered set of elements that always maintain the order in which they are initially defined (unless you sort them or otherwise modify them).
In Python, you add elements to the list in the following 4 ways (append (), extend (), insert (), + Plus).
1. Append () appends a single element to the end of the list, accepts only one parameter, the parameter can be any data type, the appended element maintains the original structure type in the list. If this element is a list, then the list will be appended as a whole, noting the difference between append () and extend ().
>>> list1=[' A ', ' B ']
>>> list1.append (' C ')
>>> List1
[' A ', ' B ', ' C ']
2. Extend () adds each element of a list to another list, accepting only one parameter, and extend () is equivalent to connecting list B to List A.
>>> List1
[' A ', ' B ', ' C ']
>>>lis2=[]
>>> list2.extend ([list1[0],list1[2]])
>>> List1
[' A ', ' C ']
Note: The difference between extend and append is that extend can add multiple elements at the same time
3. Insert () Inserts an element into the list, but its parameters are two (for example, insert (1, "G"), the first parameter is the index point, that is, where it is inserted, and the second parameter is the inserted element.
>>> List1
[' A ', ' B ', ' C ', ' d ']
>>> List1.insert (1, ' X ')
>>> List1
[' A ', ' X ', ' B ', ' C ', ' d ']
4. + Plus, add two list, return to a new list object, note the difference from the first three. The first three methods (append, Extend, insert) Add elements to the list, they do not return a value, they modify the original data object directly. Note: Adding the two lists requires creating a new list object that consumes extra memory, especially when the list is large, try not to use "+" to add the list, but use the Append () method of the list whenever possible.
>>> List1
[' A ', ' X ', ' B ', ' C ', ' d ']
>>> list2=[' y ', ' Z ']
>>> List3=list1+list2
>>> List3
[' A ', ' X ', ' B ', ' C ', ' d ', ' y ', ' Z ']
Ii. several ways to remove elements from the list in Python
li = [1,2,3,4,5,6]
# 1. Delete the corresponding subscript element using del
del Li[2]
# li = [1,2,4,5,6]
# 2. Use. Pop () to delete the last element
Li.pop ()
# li = [1,2,4,5]
# 3. Delete the element with the specified value
Li.remove (4)
# li = [1,2,5]
# 4. Use slices to delete
li = li[:-1]
# li = [1,2,3,4,5]
# !!! Do not use this method, if Li is passed as a parameter to the function,
# then using this delete method within the function will not change the original list
li = [1,2,3,4,5,6]
def Delete (Li, index):
li = li[:index] + li[index+1:]
Delete (Li, 3)
Print Li
# will output [1,2,3,4,5,6]
Several ways to add and remove elements from a list in Python