Q:

Python | Program to add an element at specified index in a list

0

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’.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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']

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now