Python - Remove Array Items



Removing array items in Python

Python arrays are a mutable sequence which means operation like adding new elements and removing existing elements can be performed with ease. We can remove an element from an array by specifying its value or position within the given array.

The array module defines two methods namely remove() and pop(). The remove() method removes the element by value whereas the pop() method removes array item by its position.

Python does not provide built-in support for arrays, however, we can use the array module to achieve the functionality like an array.

Remove First Occurrence

To remove the first occurrence of a given value from the array, use remove() method. This method accepts an element and removes it if the element is available in the array.

Syntax

array.remove(v)

Where, v is the value to be removed from the array.

Example

The below example shows the usage of remove() method. Here, we are removing an element from the specified array.

import array as arr

# creating array
numericArray = arr.array('i', [111, 211, 311, 411, 511])

# before removing array
print ("Before removing:", numericArray)
# removing array
numericArray.remove(311)
# after removing array
print ("After removing:", numericArray)

It will produce the following output

Before removing: array('i', [111, 211, 311, 411, 511])
After removing: array('i', [111, 211, 411, 511])

Remove Items from Specific Indices

To remove an array element from specific index, use the pop() method. This method removes an element at the specified index from the array and returns the element at ith position after removal.

Syntax

array.pop(i)

Where, i is the index for the element to be removed.

Example

In this example, we will see how to use pop() method to remove elements from an array.

import array as arr

# creating array
numericArray = arr.array('i', [111, 211, 311, 411, 511])

# before removing array
print ("Before removing:", numericArray)
# removing array
numericArray.pop(3)
# after removing array
print ("After removing:", numericArray)

It will produce the following output

Before removing: array('i', [111, 211, 311, 411, 511])
After removing: array('i', [111, 211, 311, 511])
Advertisements