Add an Element to Python List: Python List Operation Notes for Beginners

By | April 15, 2020

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:

Name Lily Tom John Kate
Location 0 1 2 3

If you plan to add a new member Alex at the location 2, you can do like this:

members.insert(2, 'Alex')

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.

Leave a Reply

Your email address will not be published. Required fields are marked *