Python Array – Remove specific item

Remove specific Item from Python Array

In Python, you can remove the first occurrence of specified item in an array using remove() method of the array instance.

In this tutorial, you will learn how to remove specified item in given Python array, with examples.

To remove an item x from a Python array my_array, call remove() method on the array object, and pass the item x as argument to the remove() method as shown in the following code snippet.

my_array.remove(x)

The remove() method removes the first occurrence of specified element from the array, and the array is modified.

1. Remove item 25 from the Array

In the following program, we take an integer array my_array with some initial values, and then use remove() method to remove the item 25 from this array. The item to be removed is present only once in the array.

Python Program

import array as arr

my_array = arr.array('i', [10, 15, 20, 25, 60, 20, 40])
x = 25
my_array.remove(x)

print(my_array)
Run Code Copy

Output

array('i', [10, 15, 20, 60, 20, 40])

Explanation

Array :   10, 15, 20, 25, 60, 20, 40
                       ↑
               remove 25
Result :  10, 15, 20,     60, 20, 40

2. Item to be removed has multiple occurrences in the Array

The item 20 is present twice in the array. In that case, the remove() method removes only the first occurrence.

Python Program

import array as arr

my_array = arr.array('i', [10, 15, 20, 25, 60, 20, 40])
x = 20
my_array.remove(x)

print(my_array)
Run Code Copy

Output

array('i', [10, 15, 25, 60, 20, 40])

Explanation

Array :   10, 15, 20, 25, 60, 20, 40
                  ↑
           remove 20
Result :  10, 15,     25, 60, 20, 40

3. Item to be removed is not present in the array

If we try to remove an item that is not present in the array, then the remove() method raises ValueError.

In the following program, we shall try to remove the item 99 which is not present in the array.

Python Program

import array as arr

my_array = arr.array('i', [10, 15, 20, 25, 60, 20, 40])
x = 99
my_array.remove(x)

print(my_array)
Run Code Copy

Output

  File "/Users/pythonexamplesorg/workspace/main.py", line 5, in <module>
    my_array.remove(x)
ValueError: array.remove(x): x not in array

Summary

In this Python Array tutorial, we learned how to remove specified item from the Python Array, using remove() method, with examples.

Related Tutorials

Code copied to clipboard successfully 👍