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

Add an element at the specified index in a list: In this tutorial, we will learn how to add an element/object in a list at a given/specified index with the help of examples. Which we cannot achieve using the list.append() method. By IncludeHelp Last updated : June 21, 2023

Given a Python list and we have to add an element at specified index.

How to add an element at specified index in a Python list?

The 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, you can use insert() method. The method takes two arguments (index, element) and inserts an element at the given index.

Also know: Difference b/w append() and insert() method

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

Python program to add an element at specified index in a list

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

Python List Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.