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.
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']
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']
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
0 Comments