Python 陣列 pop() 方法



Python 陣列的pop()方法用於從陣列中刪除指定索引處的元素。

此方法中,如果不提供索引值,則預設刪除最後一個元素。也可以傳遞負值作為引數。當指定的索引值超出範圍時,將得到IndexError

語法

以下是 Python 陣列pop()方法的語法:

array_name.pop(index)

引數

此方法接受整數值作為引數。

返回值

此方法返回存在於給定索引處的元素。

示例 1

以下是 Python 陣列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])

示例 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])

示例 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])

示例 4

如果給定的索引值超出範圍,則會導致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
python_array_methods.htm
廣告