CodesCompiler
🔍
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact 🚀 Get Started Free

PYTHON - Remove Array Items

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.

Thearraymodule 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 thearray moduleto achieve the functionality like an array.

Remove First Occurrence

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

Syntax

PYTHON CODE
array.remove(v)

Where,vis 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.

PYTHON CODE
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 followingoutput−

PYTHON CODE
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 thepop()method. This method removes an element at the specified index from the array and returns the element at ithposition after removal.

Syntax

PYTHON CODE
array.pop(i)

Where,iis 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.

PYTHON CODE
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 followingoutput−

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