Adding new elements to Python
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 append()
new classmate to the end of the list by using the list method:
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 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.insert (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.
Adding new elements to Python