Python - Insert an element at specific index in a list
📋 Table Of Content
In this article, we will learn about how to insert an element at a specific index in a list in python.
list in python can store multiple values in a single variable. It can hold elements of different data types like strings, integers, and other Objects.
A Python list is mutable and ordered which means each element have its own index starting from
Now, how can we alter the order of the list items by inserting an element at a specific index?
In python, we can insert an item at a specific index using the
insert() method, it takes in two arguments: first, the position at which the item will be inserted, and the second argument is the element which we want to insert.
Let's understand it with an example.
Insert an element at specific index in a list
Let's say we have a python list called animal with some strings.
animals = ['dog','cat','mouse','duck']
So the index of dog is 0, cat is 1, and so on.
Now, let's insert the string 'cow ' at index 2 using
animals = ['dog','cat','mouse','duck'] animals.insert(2,'cow') print(animals)
['dog', 'cat', 'cow', 'mouse', 'duck']
As you can see the string '
cow' is inserted at index 2 in the animals list.
Insert a list at a specific index in python list
We can also insert elements from a list at a specific index in an existing python list.
Here, we will insert elements
['frog','fish'] at index 2 in the
animals = ['dog','cat','mouse','duck'] animals2= ['frog','fish'] for item in reversed(animals2): animals.insert(2,item) print(animals)
['dog', 'cat', 'frog', 'fish', 'mouse', 'duck']
As you can see, the elements from the
animals2 list are inserted from index 2 in the Python list.
reversed() function is used because otherwise, the word "fish" would take index 2 and then the next word, which alters the ordering of the elements in
animals2 list while inserting.
There is another method that let us insert items in a list in python. We can use the
append method to insert items at the last index of the list.
Insert element at the last index in python list
We can insert an element at the last index in a list by using
append() method. We just have to pass the element as an argument in the method.
my_list = [1,2,3,4] my_list.append(5) print(my_list)
[1, 2, 3, 4, 5]
The number 5 is added at the end of the list.
Conclusion: In this article, we have learned how to use
append() methods to insert an element at a specific index or at the last index in a python list.
Remove the Last N element from a List in Python
Remove Duplicates from List in Python
Get the Index or Position of Item in List in Python