Here, we will figure out how to include a component/object in a rundown at given/determined list?
Which we can’t accomplish utilizing list.append() technique.
Given a rundown and we need to include a component at the determined list in Python.
list.append() method is utilized to affix/include a component toward the finish of the rundown. Be that as it may, in the event that we need to include a component at the determined list, we use insert() strategy. It takes 2 contentions, file and component.
Syntax:
list.insert(index, element)
Here,
- the list is the name of the rundown, where we need to insert component at the given record.
- record is, where we need to insert a component.
- the component is a component/thing to be inserted in the rundown.
Example:
list.insert(2, 100)
It will insert 100 at 2nd position in the list name ‘list’.
Program:
# Declaring a list
list = [10, 20, 30]
# printing elements
print (list)
# O/P will be: [10, 20, 30]
# inserting "ABC" at 1st index
list.insert (1, "ABC")
# printing
print (list)
# O/P will be: [10, 'ABC', 20, 30]
# inserting "PQR" at 3rd index
list.insert (3, "PQR")
# printing
print (list)
# O/P will be: [10, 'ABC', 20, 'PQR', 30]
# inserting 'XYZ' at 5th index
list.insert (5, "XYZ")
print (list)
# O/P will be: [10, 'ABC', 20, 'PQR', 30, 'XYZ']
# inserting 99 at second last index
list.insert (len (list) -1, 99)
# printing
print (list)
# O/P will be: [10, 'ABC', 20, 'PQR', 30, 99, 'XYZ']
Output:
[10, 20, 30]
[10, 'ABC', 20, 30]
[10, 'ABC', 20, 'PQR', 30]
[10, 'ABC', 20, 'PQR', 30, 'XYZ']
[10, 'ABC', 20, 'PQR', 30, 99, 'XYZ']