Add an element to a list in Python

Through this example we are going to see the different ways we can add an element to a list in Python. The first thing of all will be to define our list.

list = [1,2,3,4,5]

What we need to know to manipulate lists in Python is like accessing a specific element. Thus we have to access the value of an element we will do so by indicating its index. Thus we will print the value of the first element of the list using:

print list[0]

And to assign it will be similar:

list[0] = 9

In the case of wanting to add an element to a list in Python we can do it in two ways. The first will be using the .append() method.

list.append(6)

We simply indicate as a parameter to the .append() method the value we want to add to the list.

The second case will be playing with the index, and this will be telling it that the index is a range from size to end. This way we can add the element using.

list[len(list):] = [7]

In this case an extension is being made, so the value of the element to be added is enclosed in square brackets. Therefore it is the same as if we had used the .extend():

method

list.extend([7])

So you now have several ways to add an element to a list in Python.

Leave a Comment