Python program to delete a given element from an array(list)

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

Problem Statement

Our problem statement is, we have to delete a given element from an array (list) using python program.

For example:

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

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

Case 2: if the given array (list) is [9, 2, 4, 8] and the user gives input 4 to remove.

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

[elementor-template id=”5253″]

Our logic to delete a given element from an array(list)

  • Our program will take input to fix the size of the array (list).
  • For adding elements to the array (list), we use the ‘for loop’ and append() method.
  • Then, we take an element input from the user, which the user wants to remove from the array (list) created.
  • Print the new array (list) as the output after deleting the array.

Algorithm to delete a given element of an array(list)

Step 1: Start

Step 2: take an inputs from the user(let’s say size)

Step 3: create an empty list

Step 4: for i in range(0,size):

                     elem=int(input(“Please give value for index “+str(i)+”: “))

                     arr.append(elem)

Step 5: take the input element from the user that is needed to be removed.

Step 6:  arr.remove(num)

Step 7: print the array (list) ‘arr’.

Step 8: Stop

[elementor-template id=”5256″]

Python code to delete a given element of an array(list)

[elementor-template id=”5257″]

Output 1:

python program to delete given element from array

Explanation:

For the input array (list) [22, 43, 2, 55, 12]. The user inputs element 12 to remove from the list and our program will execute the line arr.remove(12), which searches the 12 in the array (list) and then remove that element from the array(list).

Output 2:

delete element from array python

Explanation:

For the input array (list) [12, 13, 14, 15, 76, 98]. The user inputs element 15 to remove from the list and our program will execute the line arr.remove(15), which searches the 15 in the array (list) and then remove that element from the array(list).