Inserts an item into a list at specified position
Usage
Use insert()
method to insert a single item at a specified index in a list. Note that other items are shifted to the right.
This method does not return anything; it modifies the list in place.
Syntax
list.insert(index,item)
Parameter | Condition | Description |
index | Required | Index of an item before which to insert |
item | Required | An item you want to insert |
Examples
# Insert 'yellow' at 2nd position
L = ['red', 'green', 'blue']
L.insert(1,'yellow')
print(L)
# Prints ['red', 'yellow', 'green', 'blue']
You can also use negative indexing with insert()
method.
# Insert 'yellow' at 2nd position
L = ['red', 'green', 'blue']
L.insert(-2,'yellow')
print(L)
# Prints ['red', 'yellow', 'green', 'blue']
Index greater than list length
When you specify an index greater than list length, you do not get any exception. Instead, the item is inserted at the end of the list.
L = ['red', 'green', 'blue']
L.insert(10,'yellow')
print(L)
# Prints ['red', 'green', 'blue', 'yellow']
insert() vs append()
Inserting item at the end of the list with insert()
method is equivalent to append()
method.
L = ['red', 'green', 'blue']
L.insert(len(L),'yellow')
print(L)
# Prints ['red', 'green', 'blue', 'yellow']
# is equivalent to
L = ['red', 'green', 'blue']
L.append('yellow')
print(L)
# Prints ['red', 'green', 'blue', 'yellow']
insert() vs extend()
insert()
method treats its argument as a single object.
L = ['red', 'green']
L.insert(2,'blue')
print(L)
# Prints ['red', 'green', 'blue']
Use extend() method, if you want to add every item of an iterable to a list.
L = ['red', 'green']
L.extend('blue')
print(L)
# Prints ['red', 'green', 'b', 'l', 'u', 'e']