In Python, the list insert() method is used to insert the element at the specified index in the list. The first argument is the index of the element before which to insert the element.
The following is the syntax of the list insert() method:
Let's see some examples of insert() method to understand it's functionality.
Let's see an example to insert an element at a specific position in the list.
Output:
Given List: [12, 4, 19, 22, 5] Updated List: [12, 4, 19, 14, 22, 5]
Explanation:
In this example, we are given a list. We used the insert() method to insert an element - 14 at the index value - 3. As a result, the list is updated with the inserted element.
It is possible to insert a list as an element to the list. Let us see an example where a list is inserted at specified index.
Output:
Given List: [13, 11, 9, 1, 6] Updated List: [13, 11, [3, 12, 14], 9, 1, 6]
Explanation:
In this example, we are given two lists. We used the insert() function to insert the second list in the first list at the index - 2. As a result, the list is inserted successfully.
In Python, it is possible to insert a tuple as an element to the list. Here is an example to insert the tuple in the given at specified index.
Output:
Given List: [12, 22, 14, 9, 5] Updated List: [12, 22, (1, 7, 6), 14, 9, 5]
Explanation:
In this example, we are given a list and a tuple. We used the insert() method to insert the tuple in the given list at the index - 2. As a result, the tuple is inserted to the list successfully.
In Python, we can insert a set as an element to the list. Here is an example showing how to insert a set in the list at a specific index.
Output:
Given List: [10, 18, 25, 19, 34]
Updated List: [10, 18, 25, {17, 14, 6}, 19, 34]
Explanation:
In the above example, we are given a list and set. We used the insert() method to insert the set in the list at index - 3. As a result, the set is inserted successfully.
We request you to subscribe our newsletter for upcoming updates.