insert() method is used to add an element at a specific position in a list. Unlike append() which adds elements only at the end, insert() allows adding elements anywhere in the list using an index.
Example: In this example, insert() adds "apple" at index 1 in the list.
a = ["banana", "cherry", "grape"]
a.insert(1, "apple")
print(a)
Output
['banana', 'apple', 'cherry', 'grape']
Syntax
list.insert(index, element)
Parameters:
- index: Position where the element will be inserted.
- element: Value to be added to the list.
Return: It does not return any value, but modifies the original list directly.
Examples
Example 1: In this example, an element is inserted at index 0. This places the new value at the beginning of the list.
a = ["banana", "mango"]
a.insert(0, "apple")
print(a)
Output
['apple', 'banana', 'mango']
Example 2: Here, a list is inserted as a single element inside another list, creating a nested list.
a = [1, 2, 5]
a.insert(2, [3, 4])
print(a)
Output
[1, 2, [3, 4], 5]
Example 3: In this example, the position of an existing element is found using index() and a new value is inserted before it.
a = [10, 20, 40, 50]
i = a.index(40)
a.insert(i, 30)
print(a)
Output
[10, 20, 30, 40, 50]
Explanation: a.index(40) finds the index of 40 and insert(i, 30) adds 30 before it.