Add new elements to Python
Now, there are 3 classmates in the class:
>>> L = ['Adam', 'Lisa', 'Bart']
Today, the class transferred a new classmate, Paul, how to add new students to the existing list?
The first way is to
append() append the new classmate to the end of the list using the list method:
>>> L = ['Adam', 'Lisa', 'Bart'] >>> L.append('Paul') >>> print L ['Adam', 'Lisa', 'Bart', 'Paul']
Append() always adds new elements to the end of the list.
What should I do if Paul says that he always tries to get the full score and asks to add it to the first position?
The method is to use the list
insert()method, which takes two arguments, the first argument is the index number, and the second argument 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 where the index is 0 (that is, the first one), and the Adam classmate with the original index of 0, and all the students behind, Both automatically move back one bit.