How To Add Element To List In Python?

Python provides the variable type or structure named list in order to store multiple elements. This is very similar to the arrays for other programming languages. A list may contain none or a single or more element. The element is also called an item. An element can be added to the list during list definition but can be also added after the creation of the list. In this tutorial, we will learn different methods in order to add elements to the list.

Add Element To List with append() Method

The append() method can be used to add new elements to the existing list. The element is provided as a parameter to the append() method. The element can be directly specified or provided as a parameter. The append() method adds the specified element to the end of the list.

names = ["ismail","ahmet"]


#Add element by providing it directly
names.append("ali")


name="elif"
#Add element with a variable name
names.append(name)

Add Element To List with insert() Method

Another way to add a new element to the list is the insert() method. The insert() method is very similar to the append() method but the difference is the insert() method adds the given element to the specified index.

names = ["ismail","ahmet"]


#Add element by providing it directly
names.insert("ali",2)


name="elif"
#Add element with a variable name
names.insert(name,1)

Add Element To List with extend() Method

The extend() method can be used to add an iterable list that may contain single or multiple elements to the existing list. The extend() method adds the provided iterable list element by element to the existing list. In the following example the list “names” extended with the iterable data [“ali”,”elif”].

names = ["ismail","ahmet"]


#Add element by providing it directly
names.extend(["ali","elif"])

Add Element To List with List Concatenation

As a dynamic and practical programming language Python provides the concatenation for different data structures. An existing list can be concatenated with new elements easily by using the + operator.

names = ["ismail","ahmet"]

new_names = names + ["ali"]

Leave a Comment