Python Array pop() 方法用于从数组中删除位于指定索引值的项目。
在这种方法中,如果我们不提供索引值,它将默认删除最后一个元素。负值也可以作为参数传递给此方法。当指定的索引值超出范围时,我们将收到 IndexError。
语法
以下是 Python Array pop() 方法的语法 -
参数
此方法接受整数值作为参数。
返回值
此方法返回位于给定索引中的项目。
示例 1
以下是 Python Array pop() 方法的基本示例 -
输出
以下是上述代码的输出 -
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() 方法中传递参数 -
输出
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
在这种方法中,我们还可以将负索引值作为参数传递。下面是一个示例 -
输出
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。让我们通过以下示例来理解 -
输出
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