What is the array remove() function in Python?

Overview

An array in Python is used to store multiple values of the same type in a single variable.

The remove() function is used to remove the first occurrence of a value in a given array. In simple terms, the remove() function removes the first occurrence of an element (if there are other elements of the same value) in an array and will not display that element in the array. The method will show the other occurrences of that element when the array is printed.

Syntax

array.remove(x)

Parameters

  • x: the element you want to remove from a given array.

Return value

The remove() function returns an array without the first occurrence of the specified element or value that was passed as a parameter.

Example

Now, let’s use the remove() function to remove the first occurrence of a specified element from a given array.

# importing the array module
from array import array
# creating an integer data type array
myArray = array('i', [1,2,3,4,5,6,1,2,3,2,4,7])
# using the remove() function to remove the 1st 2 from the array
myArray.remove(2)
myArray.remove(7)
# printing the new array
print('The new array after element 2 and 7 have been removed is: ', myArray)

Notice from the output of the code above that one of the elements that was removed from the original array was the first occurrence of the value 2, and not all the values of 2 in the array. The other element that is deleted is 7.

Free Resources