In this article, we will see how to insert an element at the end of a list in python.
Inserting at the end is pretty similar to how to insert at the beginning of a list. We use an insert() method, which will take two arguments i.e. index and the value to be inserted.
List stores elements in a contagious manner. The indexing starts from 0 and ends at N – 1. Here, N is the size of the list.
To insert at end of a list, We need to pass the index value as “size of the list”.
For example, let’s assume we have the following list:
# Create a list
fruits = ['apple', 'banana', 'grape', citrus']
The length of the above list is 4 and the position where we wanted to insert the element into the list is 4. So, we can pass the size of a list as an index to insert the end of the list.
# Create a list fruits = ['apple', 'banana', 'grape', citrus'] print(fruits) #insert at the end of a list fruits.insert(len(fruits), 'orange') print(fruits)
Similar to the insert()
we also have an append()
method which automatically inserts at the end of the list.
Following is the example:
# Create a list
fruits = ['apple', 'banana', 'grape', citrus']
print(fruits)
#insert at the end of a list
fruits.append('orange')
print(fruits)