Python Remove Array Item
Removing items from an array can be a common task, and there are several ways to accomplish this depending on the specific needs of your application. This article will cover different methods to remove items from an array in Python.
Remove specific array item
The remove() method removes the first occurrence of a specified value from the array. If the value is not found, it raises a ValueError.
import array
# Create an array of integers
arr = array.array('i', [1, 2, 3, 4, 5])
# Remove the first occurrence of the value 3
arr.remove(3)
print(arr)
Output
array('i', [1, 2, 4, 5])
Let's take a look at other cases of removing item from an array:
Table of Content
Using Slicing to remove item
You can use slicing to remove elements from an array by creating a new array that excludes the elements you want to remove. This method is useful when you need to remove items at specific positions.
import array
# Create an array of integers
arr = array.array('i', [1, 2, 3, 4, 5])
# Remove the element at index 2 (third element)
arr = arr[:2] + arr[3:]
print(arr)
Output
array('i', [1, 2, 4, 5])
Remove item at specific index - Using pop()
The pop() method removes an element at a specified index and returns it. If no index is specified, it removes and returns the last element of the array.
import array
# Create an array of integers
arr = array.array('i', [1, 2, 3, 4, 5])
# Remove the element at index 2 and return it
val = arr.pop(2)
print(arr)
print(val)
Output
array('i', [1, 2, 4, 5]) 3
Using List Comprehension
Although this method is more suited to lists, it can also be used with arrays for more complex removal operations such as removing all occurrences of a value.
import array
# Create an array of integers
arr = array.array('i', [1, 2, 3, 2, 4, 2, 5])
# Remove all occurrences of the value 2
arr = array.array('i', [x for x in arr if x != 2])
print(arr)
Output
array('i', [1, 3, 4, 5])