Python - How to add an element at specific index in list

Published May 13, 2021


In this python programming example we will cover how to add an element/object at specific index position. To add an element in  list we will use list.append() method. To add element at specific index we will use insert() method.

Syntax

list.insert(index, element)

 

The above insert method requires two arguments

index: is the position, where we want to insert an element

element: is an element to be inserted in the list

 

Example

# Define a list with elements
list = [1, 2, 3]

# print elements
print (list)


# insert "abc" at 1st index
list.insert (1, "abc")
# printing
print (list)


# insert "xyz" at 3rd index
list.insert (3, "xyz")
# printing
print (list)


# insert 'python' at 5th index
list.insert (5, "python")
print (list)


# insert 99 at second last index
list.insert (len (list) -1, 99)
# printing
print (list)

 

 

Output:

Above example will print below output

[1, 2, 3]
[1, 'abc', 2, 3]
[1, 'abc', 2, 'xyz', 3]
[1, 'abc', 2, 'xyz', 3, 'python']
[1, 'abc', 2, 'xyz', 3, 99, 'python']

 

Related:

How to concatenate strings in python

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

84 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions