Add item at a specific position in a Python List
In this post, we will learn to an element to a list at a specific index or position. We are using List.insert() function to do that.
In Python, lists are used to store multiple elements and access them using their index. Lists are mutable means you can add or delete items to them. You can add an item to the list using several ways but if you want to add an item at a specific position, you need to use the List.insert() function.
Let's create a list first
my_list = ["Troy", "John", "Steve", "Johana"]
We have created a list my_list here that contains multiple String values in it. Our task is to add a new String value to this list at 3rd position.
Add an item at a specific index of a list using List.insert() function
The List.insert() function can be used to add an item to a list at a given position. It takes two arguments. The first argument is the index - starts from 0 and the second argument is the item that you want to add.
Syntax
List.insert(index, item)
Code example of insert() function
# create a list
my_list = ["Troy", "John", "Steve", "Johana"]
# add element at third position
my_list.insert(2, 'Carl')
# print the list
print(my_list)
Output
['Troy', 'John', 'Carl', 'Steve', 'Johana']
Add item at the first position of a list using insert() function
As we know that if we know the index of a list, we can add a new item to that list using the insert() function. Here we will add an element to the first position of the list. We will use the index value as 0 to add the item.
Code example
# create a list
my_list = ["Troy", "John", "Steve", "Johana"]
# add element at the first position
my_list.insert(0, 'Stark')
# print the list
print(my_list)
Output
['Stark', 'Troy', 'John', 'Steve', 'Johana']
Add an item to the last of a list using the insert() function
We can also use the insert() function to add the element at the last position of the list. We will use the len() function of python along with the insert() function to do that.
Code example
# create a list
my_list = ["Troy", "John", "Steve", "Johana"]
# add element at the first position
my_list.insert(len(my_list), 'Stark')
# print the list
print(my_list)
Output
['Troy', 'John', 'Steve', 'Johana', 'Stark']
Full code example
- Remove items less than a specific value from Python list
- Get count of a specific element in a list using Python
- Replace DataFrame column values with a specific value
- remove rows base on NaN of specific column
- Select specific columns from a Pandas DataFrame
- Get last item or value from a List in python
- Remove an item from python list using its index