Press "Enter" to skip to content

Python program to remove the first occurrence of a specified element from an array

In this post, we will look at the python program to remove the first occurrence of a specified element from an array.

Let’s look at sample input and output.

Input: [10, 30, 60, 30, 90]
We have to remove the first occurrence of 30 from the array. 
So, the output should be as below.
Output: [10, 60, 30, 90]

Python Program

We are going to make use of the remove() method provided by python.
remove() method takes the value to remove from the array.
Let’s look at the program now.

# python program to remove
# the first occurrence of an element
from array import *

array_int = array('i', [99, 55, 77, 33, 55, 66 ])

# print original values
print("Values in array: "+str(array_int))

print("Removing first occurrence of 55.")
array_int.remove(55)

print("Modified array: "+str(array_int))
Freshers Placement

Output

Values in array: array('i', [99, 55, 77, 33, 55, 66])
Removing first occurrence of 55.
Modified array: array('i', [99, 77, 33, 55, 66])

Algorithm
Step 1: Declare and initialize the array
Step 2: Call the remove() method to remove 55 from the array
Step 3: Print the modified array

Note: remove() method throws ValueError when the value to remove is not present in an array.
ValueError: array.remove(x): x not in array

Comments are closed.