The insert()
method in Python is a List method used to insert an element at a specified index. It takes two arguments - the index where the element needs to be inserted, and the element itself. The remaining elements are shifted to the right, and the length of the list increases by 1.
Parameter Values
Parameter | Description |
---|---|
index | The position where the element is to be inserted. |
element | The element to be inserted into the list. |
Return Values
The insert()
method has no return value; it returns None
.
How to Use insert()
in Python
Example 1:
The insert()
method inserts an element into a list at the specified index. Elements at subsequent indexes are shifted to the right.
numbers = [1, 2, 3, 4]
numbers.insert(2, 100)
print(numbers) # Output: [1, 2, 100, 3, 4]
Example 2:
If the index is out of range, it will raise an IndexError.
colors = ['red', 'green', 'blue']
colors.insert(5, 'yellow')
print(colors) # Output: IndexError: list insert index out of range
Example 3:
The insert()
method can also be used to add elements at the beginning of the list by specifying index 0.
animals = ['lion', 'elephant', 'zebra']
animals.insert(0, 'tiger')
print(animals) # Output: ['tiger', 'lion', 'elephant', 'zebra']