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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.