Removing Array Items in Python: Methods and Techniques
Discover how to remove items from Python arrays using methods like remove()
and pop()
. Learn how to delete elements by value or position with practical examples and code snippets.
Removing Array Items in Python
Python arrays are mutable sequences, allowing easy addition and removal of elements. You can remove an element by specifying its value or position. The array
module provides two methods: remove()
and pop()
. The remove()
method removes an element by value, while the pop()
method removes an element by its position.
Remove First Occurrence
To remove the first occurrence of a value, use the remove()
method. This method accepts an element and removes it if available in the array.
Syntax
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)
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 element from a specific index, use the pop()
method. This method removes an element at the specified index and returns it.
Syntax
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)
Output
Before removing: array('i', [111, 211, 311, 411, 511])
After removing: array('i', [111, 211, 311, 511])