Home »
Python programs
Python | Program to add an element at specified index in a list
Here, we are going to learn how to add an element/object in a list at given/specified index? Which we cannot achieve using list.append() method.
Submitted by IncludeHelp, on July 20, 2018
Given a list and we have to add an element at specified index in Python.
list.appened() Method is used to append/add an element at the end of the list. But, if we want to add an element at specified index, we use insert() method. It takes 2 arguments, index and element.
Syntax:
list.insert(index, element)
Here,
- list is the name of the list, in which we have to insert element at given index.
- index is the position, where we want to insert an element.
- element is an element/item to be inserted in the list.
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']
TOP Interview Coding Problems/Challenges