# The insert() method inserts an element to the list
# at a given index.
# Syntax: list_name.insert(index, element)
my_list = ["Add", "Answer"]
my_list.insert(1, "Grepper")
print (my_list)
> ['Add', 'Grepper', 'Answer']
#add item to the beginning of list – at index 0
clouds = [‘Cisco’, ‘AWS’, ‘IBM’]
clouds.insert(0, ‘Google’)
print(clouds)
[‘Google’, ‘Cisco’, ‘AWS’, ‘IBM’]
#add item to the end of list
a.insert(len(a),x) is equivalent to a.append(x)
clouds = [‘Cisco’, ‘AWS’, ‘IBM’]
clouds.insert(len(clouds), ‘Google’)
print(clouds)
[‘Google’, ‘Cisco’, ‘AWS’, ‘IBM’]
#add item to specific index
number_list = [10, 20, 40] # Missing 30.
number_list.insert(2, 30 ) # At index 2 (third), insert 30.
print(number_list) # Prints [10, 20, 30, 40]
number_list.insert(100, 33)
print(number_list) # Prints [10, 20, 30, 40, 33]
number_list.insert(-100, 44)
print(number_list) # Prints [44, 10, 20, 30, 40, 33]
FOMAT: list.insert(index,element)
hey you, I want you to remember that insert function
takes the index as the parameter okay?
Just remember it as "insert" starts with "i" so the first parameter of insert
also starts with i
Sounds crazy but works...have a good day. Dont forget this concept.
# Inserting multiple items in a list at a specific index
# list.insert()
myList = [1, 2, 3]
myList[1:1] = ['One', 'Two']
print(myList)
# [1, 'One', 'Two', 2, 3]
# Python program to demonstrate
# Addition of elements in a List
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("
List after performing Insert Operation: ")
print(List)
# Python program to demonstrate
# Addition of elements in a List
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(0, 0)
List.insert(5, 'Softhunt.net')
print("
List after performing Insert Operation: ")
print(List)