Python list can save elements, we should add an element to it. In this tutorial, we will discuss how to add data to python list.
There are several ways to add an element to a python list, we will introduce one by one.
Add an element to the end of python list
This is the most common way to add an element to a python list. For example, if you have a python list members, this list has contained three members: Lily, Tom and John. You want to add a new member kate to it, you can do like this:
members = ['Lily', 'Tom', 'John'] members.append('Kate') print(members)
Run this result, you will get the result:
['Lily', 'Tom', 'John', 'Kate']
You will find the new member Kate has been added to the end of list members.
Add an element to a list by position
As to list members above, the location of all members in this list is:
If you plan to add a new member Alex at the location 2, you can do like this:
The result will be:
['Lily', 'Tom', 'Alex', 'John', 'Kate']
We can insert an element to a list by list.insert() function.
You should notice: if the location is bigger than the lenght of list, new element will be inserted to the end of python list.
Here is an example:
members.insert(9, 'Alex') print(members)
Where 9 is better than the length of list members, which is 4. Run this code, you will get the result:
['Lily', 'Tom', 'John', 'Kate', 'Alex']
Alex will be inserted at the end of list members.