Python List insert() method
Python List insert() method
The list.insert () method in Python inserts an item at the specified position.
Syntax
list.insert(i, x)
Parameter
i: This parameter represents a number specifying the position to insert the given value.
x: This parameter signifies an element of any type (string, number, object etc.)
Example 1
# Python program explaining # the list.insert() method listVal = [ 11, 12, 13, 14, 15, 16, 17 ] # insert 19 at 2th position listVal.insert(2, 19) print(listVal) strVal = ['a', 'b', 'c', 'd', 'e'] # insert z at the end of the list strVal.insert(4, 'z') print(strVal)
Output
[11, 12, 19, 13,14, 15, 16, 17] ['a', 'b', 'c', 'd', 'z', 'e']
Example 2
# Python program explaining # the list.insert() method fruitVal = ['apple', 'banana', 'cherry'] print("Fruit list: \n",fruitVal) # inserting more fruits in the list print("After inserting more fruits in the list: ") fruitVal.insert(4, "Kiwi") fruitVal.insert(5, "orange") fruitVal.insert(6, "Fig") print(fruitVal)
Output
Fruit list: ['apple', 'banana', 'cherry'] After inserting more fruits in the list: ['apple', 'banana', 'cherry', 'Kiwi', 'orange', 'Fig']