Python (3) Addition, deletion and modification of List

One data type built into Python is a list: list. A list is an ordered collection from which elements can be added and removed at any time. A list is an ordered collection in the mathematical sense, that is, the elements in a list are arranged in order. Constructing a list is very simple. According to the above code, directly enclose all elements of the list with [ ], which is a list object. Usually, we assign list to a variable, so that we can refer to the list through the variable:

 L = ['Adam', 'Lisa', 'Bart']
 >>> print L[0]
 output:  Adam
  • Another way: access the list in reverse order
>>> print L[-1]
output: Bart

add new element

  • The first method is to use the append() method of the list to append new students to the end of the list
>>> L = ['Adam', 'Lisa', 'Bart']
>>> L.append('Paul')
>>> print L
['Adam', 'Lisa', 'Bart', 'Paul']
  • The insert() method of list, which accepts two parameters, the first parameter is the index number, and the second parameter is the new element to be added:
>>> L = ['Adam', 'Lisa', 'Bart']
>>> L.insert(0, 'Paul')
>>> print L
['Paul', 'Adam', 'Lisa', 'Bart']

L.insert(0, 'Paul') means that 'Paul' will be added to the position with an index of 0 (that is, the first one), and Adam with the original index of 0, and all the following students, are automatically moved one bit backwards.

delete element from list

  • If Paul is the last one, we can delete it with the pop() method of the list:
 L = ['Adam', 'Lisa', 'Bart', 'Paul']
 L.pop()
'Paul'
 print L
['Adam', 'Lisa', 'Bart']

The pop() method always deletes the last element of the list, and it also returns that element, so after we do L.pop(), it prints 'Paul'.

L=['Adam','Lisa','Bart']
L.pop()
print(L)

Result: ['Adam', 'Lisa']

  • What if classmate Paul is not the last in line? For example, Paul ranked third:
 L = ['Adam', 'Lisa', 'Paul', 'Bart']

To kick Paul off the list, we must first locate Paul's position. Since Paul's index is 2, use pop(2) to delete Paul:

replace element

  • The first method is to delete first, then add
L = ['Adam', 'Lisa', 'Bart']
L.pop()
L.insert(2,'Paul')
print(L)

Output result: ['Adam', 'Lisa', 'Paul']
- the second method directly replaces

L = ['Adam', 'Lisa', 'Bart']
L[-1]='Paul'
print(L)

Result: ['Adam', 'Lisa', 'Paul']

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325733815&siteId=291194637