What is the array pop() method in Python?
Overview
An array stores multiple values, items, and elements of the same data type in a single variable.
The pop method removes an item from an array using the index value or the position of the item in the given array.
Syntax
array.pop([i])
Parameter value
The pop() method takes the item’s index position to be removed from the given array. If we do not provide any parameter, the last value from the array will be removed by default.
Return value
The pop() method returns an array after removing the specified element or item from the original array.
Example
# importing the array moduleimport array as arr# creating an integer data type arrayx = arr.array('i', [1,2,3,4,5,6,7])# using the pop method to remove index 2 of the arrayx.pop(2)# printing the new arrayprint(x)
Explanation
-
Line 1: We import the
arraymodule and assign the aliasarrto it. -
Line 5: We create an array variable,
x, of the integer type (irepresents integer data type) using thearr.array()function. -
Line 8: We invoke the
pop()method onxand pas the index value 2. It will remove the element from the array present at the specified index. -
Line 11: We print the array,
x, after removing the element.
It is worthy to note that in Python, an array starts at index 0.