Arrays in Python are homogeneous, type-code specific, memory optimized and indexed based sequential data structure. Array is a most fundamental and memory efficient data structure in Python Programming Language. Array
module provides remove()
and pop()
methods and del
operator to remove elements from an array. Lets see what is the meaning of remove, pop and del.
remove
– It means element is removed. Element will not be returned.pop
– It means element will be taken out. Element will be removed and will be returned.del
– This deleted the entire object. Generally used to delete the array itself.
remove()
method
Removing an element from a collection (array, list, tuple,set or dictionary) is a basic operation that we need to perform. Python array
module provides remove()
method to remove an element from an array object. Syntax for remove()
method:
return_value = array_object.remove(element)
array_object
is an array (specific to type-code) from which we want to remove an element.remove
is name of the methodelement
is the element to be removed from the array. This element should be present in the array, otherwise we will get ValueError.- This method does not return any value (return
None
). Soreturn_value
will beNone
. array_object
will reference the array after removing the element.
remove()
method
Remove element – # remove method - remove signed long
print("remove method - remove signed long")
import array as array # import array module
signed_long_array = array.array("l", [-18934898, 23478783, -3892839, -4378734, 38989347]) # signed long array
print(signed_long_array)
return_value = signed_long_array.remove(-3892839) # remove element using remove() method
print(signed_long_array)
print(return_value)
In this program, first we are importing the array
module. We are declaring and initializing an array with type-code l (signed long)
. This array is referenced by variable signed_long_array
. We are using signed_long_array.remove(-3892839)
to remove element -3892839
from the array. This element is present in the array and will be removed successfully. remove()
method does not return any value. return_value
will be None
.
Program Output
remove method - remove signed long
array('l', [-18934898, 23478783, -3892839, -4378734, 38989347])
array('l', [-18934898, 23478783, -4378734, 38989347]) # array elements after removal
None # return value None
From the output, element -3892839
has been removed from the array and None
is returned.
ValueError
– remove()
method
Using remove()
method, if the element to be removed from an array is not present in array, then ValueError
is raised (thrown).
# ValueError - element to remove not in array
print("ValueError - element to remove not in array")
import array as array # import array module
integer_array = array.array("i", [10, -20, -30, 40]) # array with type-code i (signed integer)
print(integer_array)
integer_array.remove(50.89) # remove element using remove() method
We have declared and initialized an array integer_array
with type-code i (integer)
. We are using integer_array.remove(50.89)
to remove an element from the array. Element 50.89
is not present in the array integer_array
. remove()
method will raise (throw) a ValueError
when element is not present in array.
Program Output
ValueError - element to remove not in array
array('i', [10, -20, -30, 40])
Traceback (most recent call last):
File "D:\remove-element-array.py", line 18, in <module>
integer_array.remove(50.89)
ValueError: array.remove(x): x not in array
From the program output, element 50.89
is not present in the array. remove()
method raised (thrown) a ValueError
. ValueError: array.remove(x): x not in array
remove()
method
Custom implementation – Array datatype are of fixed size. New elements can be removed by creating another array of decreased size and copying all the elements (except element to remove) of existing array into the new array. We will see the custom implementation logic to remove element from the array.
# Custom implementation - remove element from an array
print("Custom implementation - remove element from an array")
import array as array
def custom_remove(array_object, element):
new_array_object = array.array(array_object.typecode, [0] * (len(array_object) - 1))
element_found = False
for x in range(len(new_array_object)):
if array_object[x] == element:
element_found = True
if element_found:
new_array_object[x] = array_object[x+1]
else:
new_array_object[x] = array_object[x]
if not element_found:
raise ValueError("custom_remove(arr, x): x not in arr")
return new_array_object
integer_array = array.array("i", [10, -20, -30, 40])
print(integer_array)
integer_array = custom_remove(integer_array, -30)
print(integer_array)
Lets understand the step by step implementation of this program.
- We are importing
array
module. This is to read the original array object and to create the new array object. - We are defining a method
custom_remove(array_object, element)
method. This method will take two argumentsarray_object
=> original array object from which element to be removed,element
to be removed - Crew a new array
new_array_object
of same type-code and of reduced length. Usingarray_object.typecode
, type-code value is taken fromarray_object
itself. - Declare a variable
element_found
, with initial value as False. This is to check ifelement
(to be removed) found inarray_object
or not. - Using
for
loop andrange()
method withnew_array_object
, iterate through the index positions of an array. - Add logic to check if element found or not in the array and copy elements in new array based on the condition.
- If element not found in the array, then raise
ValueError
. - Finally, return the new array object with element removed from the
array_object
. - Assign reference to this returned object with
integer_array
(same variable which was referring to old array object). - Print the value of the new array with removed element.
- For example => we are passing an array with type-code
i (signed integer)
and remove element-30
from the array.
Program Output
Custom implementation - remove element from an array
array('i', [10, -20, -30, 40])
array('i', [10, -20, 40]) # removed element -30 from array
From the program output, element -30
has been removed from the array.
pop()
method
Similar to remove()
method, we have another method pop()
. pop()
method can also be used to take out an element from the array. pop()
method take out element based on the index position from an array. Syntax for pop()
method:
pop_element = array_object.pop(index)
array_object
is an array (specific to type-code) from which we want to remove (pop) an element.pop
is name of the methodindex
is the index position.pop()
method takes index position of an element to be removed from the array. This index should be present in the array, otherwise we will get IndexError.pop_element
is the return value of element that has been removed from array.array_object
will reference the array after removing the element.pop()
can take both Positive Index and Negative Index positions.
pop()
method
Pop element – # pop method - pop index element
print("pop method - pop index element")
import array as array # import array module
signed_long_array = array.array("l", [-18934898, 23478783, -3892839, -4378734, 38989347])
print(signed_long_array)
pop_element = signed_long_array.pop(-3) # pop element at index -3
print(signed_long_array)
print(pop_element)
In this program, first we are importing the array
module. We are declaring and initializing an array with type-code l (signed long)
. This array is referenced by variable signed_long_array
. We are using signed_long_array.pop(-3)
to take out element at index position -3
from the array. This index is present in the array and element at that index will be removed from the array. pop()
method will return the removed element. pop_element
value will be -3892839
.
Program Output
pop method - pop index element
array('l', [-18934898, 23478783, -3892839, -4378734, 38989347])
array('l', [-18934898, 23478783, -4378734, 38989347]) # remove element at index -3
-3892839 # removed element
From the program output, element at index position -3
has been removed from the array. Removed element -3892839
from index -3
was returned.
IndexError
– pop()
method
Using pop()
method, if the given index (either Positive Index or Negative Index) does not exists in array, then IndexError
is raised (thrown).
# IndexError - index out of range
print("IndexError - index out of range")
import array as array # import array module
integer_array = array.array("i", [10, -20, -30, 40]) # defined array with type-code i (signed integer)
print(integer_array)
try:
pop_element = integer_array.pop(8) # pop element at index 8
except IndexError as err: # catch IndexError
print("error", err)
print(integer_array)
We have declared and initialized an array integer_array
with type-code i (integer)
. We are using integer_array.pop(8)
to take out an element from the array at index 8
. Index position 8
does not exist in the array integer_array
. pop()
method will raise (throw) a IndexError
when given index is not present in array. We have catch and printed the error.
Program Output
IndexError - index out of range
array('i', [10, -20, -30, 40])
error pop index out of range # IndexError
array('i', [10, -20, -30, 40])
From the program output, index 8
does not exist in the array. pop()
method raised (thrown) a IndexError
. IndexError: pop index out of range
del
operator
del
operator is used to delete any object in Python. del
operator can delete array, list, tuple, set, dictionary and other objects as well.
del
operator
Delete array object – # del - delete array
print("del - delete array")
import array as array
integer_array = array.array("i", [10, 20, 30, 40])
print(integer_array)
del integer_array # delete array object
print(integer_array) # will throw error, after delete array object does not exist
Program Output
del - delete array
array('i', [10, 20, 30, 40])
Traceback (most recent call last):
File "D:\remove-element-array.py", line 89, in <module>
print(integer_array)
^^^^^^^^^^^^^
NameError: name 'integer_array' is not defined
From the program output, integer_array
object was deleted using the del
operator. We got a NameError
, because array object no longer exists after deleting it. NameError: name 'integer_array' is not defined
del
operator
Delete array element – We can use del
operator to delete a single or a slice of elements from the array.
# del - delete element from an array
print("del - delete element from an array")
import array as array
integer_array = array.array("i", [1540, 245450, 345450, 445450, 89839, 236762])
print(integer_array)
del integer_array[2] # delete element at index 2
print(integer_array)
del integer_array[1:3] # delete slice of elements from index 1 to 3 (excluding)
print(integer_array)
In this program, we have declared an array integer_array
with type-code i (signed integer)
. This array has 6 elements in it. We are performing two delete operations.
- First, using
del integer_array[2]
we are deleting a single element at index2
from this array. - Second, using
del integer_array[1:3]
we are deleting multiple elements (slice of elements) from this array. This will remove elements from index 1 to 3 (excluding) from this array.
Program Output
del - delete element from an array
array('i', [1540, 245450, 345450, 445450, 89839, 236762])
array('i', [1540, 245450, 445450, 89839, 236762]) # array after deleting index 2 element
array('i', [1540, 89839, 236762]) # array after deleting slice index 1:3
From the program output, first element 345450
got removed because this was at index 2
position in the array. Second, element 245450, 445450
got removed from the array because they are at index 1 to 3 (excluding) in the array.
Summary
In this article, we learned about remove()
and pop()
methods and del
operator. Following scenarios we discussed: