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 module
import array as arr
# creating an integer data type array
x = arr.array('i', [1,2,3,4,5,6,7])
# using the pop method to remove index 2 of the array
x.pop(2)
# printing the new array
print(x)

Explanation

  • Line 1: We import the array module and assign the alias arr to it.

  • Line 5: We create an array variable, x, of the integer type (i represents integer data type) using the arr.array() function.

  • Line 8: We invoke the pop() method on x and 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.

Free Resources