Append () and insert ()
Add new Element
Now, there are 3 students in the class:
>>> L = [' Adam ', ' Lisa ', ' Bart ']
Today, the class transferred to a new classmate Paul, how to add new students to the existing list?
The first option is to append the new classmate to the end of the list by using the Append () method of the list:
>>> L = [' Adam ', ' Lisa ', ' Bart ']
>>> l.append (' Paul ')
>>> Print L
[' Adam ', ' Lisa ', ' Bart ', ' Paul ']
Append () always adds a new element to the tail of the list.
What if Paul says he is always on the test and asks to be added to the first place?
The method is to use the list's insert () method, 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 ']
>>> LInsert (0, ' Paul ')
>>> Print L
[' Paul ', ' Adam ', ' Lisa ', ' Bart ']
L.insert (0, ' Paul ') means that ' Paul ' will be added to the position of index 0 (i.e. the first one), while Adam, who originally indexed 0, and all the classmates behind it, automatically move backwards.
Python list Add new element