Python Array pop() 方法用于从数组中删除位于指定索引值的项目。
在这种方法中,如果我们不提供索引值,它将默认删除最后一个元素。负值也可以作为参数传递给此方法。当指定的索引值超出范围时,我们将收到 IndexError。
语法
以下是 Python Array pop() 方法的语法 -
array_name.pop(index)
参数
此方法接受整数值作为参数。
返回值
此方法返回位于给定索引中的项目。
示例 1
以下是 Python Array pop() 方法的基本示例 -
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)
输出
以下是上述代码的输出 -
Array Elements Before Poping : array('i', [100, 220, 330, 540])
Array Elements After Poping : array('i', [100, 220, 540])
Array Elements After Poping : array('i', [100, 220, 540])
示例 2
如果我们不向此方法传递任何参数,它会从数组中删除最后一个元素,即 -1 元素。
在下面的示例中,我们没有在 pop() 方法中传递参数 -
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)
输出
Array Elements Before Poping : array('i', [22, 32, 42, 52])
Array Elements After Poping : array('i', [22, 32, 42])
Array Elements After Poping : array('i', [22, 32, 42])
示例 3
在这种方法中,我们还可以将负索引值作为参数传递。下面是一个示例 -
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)
输出
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])
Array Elements After Poping : array('d', [22.3, 5.2, 7.2, 9.2, 6.7, 11.1])
示例 4
如果给定索引值 index value is out of range,则会导致 IndexError。让我们通过以下示例来理解 -
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)
输出
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
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