Python Array pop() Method



The Python array pop() method is used to remove an item at the specified index value from an array.

In this method, If we will not provide a index value it will remove the last element by default . A negative value can also be passed as a parameter to this method. When the specified index value is out of range then we will get IndexError.

Syntax

Following is the syntax of the Python Array pop() method −

array_name.pop(index)

Parameters

This method accepts integer value as a parameter.

Return Value

This method return the item that present at the given index.

Example 1

The following is the basic example of the Python array pop() method −

import array as arr
#Creating an array
my_array1 = arr.array('i',[100,220,330,540])
#Printing the elements of an array
print("Array Elements Before Poping : ", my_array1)
index=2
my_array1.pop(index)
print("Array Elements After Poping : ", my_array1)

Output

Following is the output of the above code −

Array Elements Before Poping :  array('i', [100, 220, 330, 540])
Array Elements After Poping :  array('i', [100, 220, 540])

Example 2

If we do not pass any argument to this method, it removes the last element i.e -1 element from an array.

Here in the following example we didn't pass the argument in pop() method −

import array as arr
#Creating an array
my_array2 = arr.array('i',[22,32,42,52])
#Printing the elements of an array
print("Array Elements Before Poping : ", my_array2)
my_array2.pop()
print("Array Elements After Poping : ", my_array2)

Output

Array Elements Before Poping :  array('i', [22, 32, 42, 52])
Array Elements After Poping :  array('i', [22, 32, 42])

Example 3

In this method, We can also pass negative index value as an argument. Here is an example −

import array as arr
#Creating an array
my_array3 = arr.array('d',[22.3,5.2,7.2,9.2,2.4,6.7,11.1])
#Printing the elements of an array
print("Array Elements Before Poping : ", my_array3)
index=-3
my_array3.pop(index)
print("Array Elements After Poping : ", my_array3)

Output

Array Elements Before Poping :  array('d', [22.3, 5.2, 7.2, 9.2, 2.4, 6.7, 11.1])
Array Elements After Poping :  array('d', [22.3, 5.2, 7.2, 9.2, 6.7, 11.1])

Example 4

If the index value is given index value is out of range, it will result in IndexError. Lets understand with following example −

import array as arr
#Creating an array
my_array4 = arr.array('i',[223,529,708,902,249,678,11])
#Printing the elements of an array
print("Array Elements Before Poping : ", my_array4)
index=8
my_array4.pop(index)
print("Array Elements After Poping : ", my_array4)

Output

Array Elements Before Poping :  array('i', [223, 529, 708, 902, 249, 678, 11])
Length of an array is: 7
Traceback (most recent call last):
  File "E:\pgms\Arraymethods prgs\pop.py", line 57, in <module>
    my_array4.pop(index)
IndexError: pop index out of range
python_array_methods.htm
Advertisements