Python Program to Insert element at given location in array(list)

Python program to insert an element at a given location of an array(list)

In this tutorial, we will learn writing the python program to insert an element at the given position of an array (list in case of python) and print the array (list).

Problem Statement

Our problem statement is, for a given array(list) we have to add an element at the given position (index).

For example:

Case 1: if the given array (list) is [1, 2, 3, 4] and the user gives input 9 to add at index 2.

              The output should be [1, 2, 9, 3, 4].

Case 2: if the given array (list) is [9, 2, 4, 8] and the user gives input 10 to add at index 1.

               The output should be [9, 10, 2, 4, 8].

Our logic to insert an element at a given location of an array(list)

  • Our program will take two inputs from the user, one is the elements and the other is the location ( position or index) of the element where the user wants the element to insert.
  •  Then, use insert() built-in method with the user inputs as an argument to insert new element at given location. After insertion print the output.

Algorithm to insert an element at a given location of an array(list)

Step 1: Start

Step 2: take two inputs from the user(let’s say element and position)

Step 3: if index >= len(arr):

                    print(“please enter index smaller than”,len(arr))

else:

                    arr.insert(index, num) 

Step 4: print the array (list)

Step 5: Stop

Python code to insert an element at a given location of an array(list)

Output 1:

Explanation:

For the given array (list) [1, 2, 3, 4, 5], the user inputs element 5 to add at the index 2 of the array (list). using the insert() method, our program will easily add element 5 at the desired location of the list and returns the updated list.

Output 2:

Explanation:

For the given array (list) [1, 2, 3, 4, 5], the user inputs element 10 to add at the index 4 of the array (list). using the insert() method, our program will easily add element 10 at the desired location of the list and returns the updated list.