Python 列表 pop() 方法



Python 列表pop()方法預設刪除並返回列表中的最後一個物件。但是,該方法也接受可選的索引引數,並且將刪除列表中索引處的元素。

此方法與remove()方法的區別在於,pop()方法使用索引技術刪除物件,而remove()方法遍歷列表以查詢物件的第一次出現。

語法

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

list.pop(obj = list[-1])

引數

  • obj − 這是一個可選引數,要從列表中刪除的物件的索引。

返回值

此方法返回從列表中刪除的物件。

示例

以下示例演示了 Python 列表 pop() 方法的用法。在這裡,我們沒有向方法傳遞任何引數。

aList = [123, 'xyz', 'zara', 'abc']
print("Popped Element : ", aList.pop())
print("Updated List:")
print(aList)

執行上述程式時,會產生以下結果:

Popped Element :  abc
Updated List:
[123, 'xyz', 'zara']

示例

但是,如果我們向方法傳遞索引引數,則返回值將是在給定索引處刪除的物件。

aList = ['abc', 'def', 'ghi', 'jkl']
print("Popped Element : ", aList.pop(2))
print("Updated List:")
print(aList)

如果我們編譯並執行上面的程式,則輸出將顯示如下:

Popped Element :  ghi
Updated List:
['abc', 'def', 'jkl']

示例

眾所周知,Python 允許負索引,並且從右到左進行。因此,當我們將負索引作為引數傳遞給方法時,將刪除該索引處的元素。

aList = [123, 456, 789, 876]
print("Popped Element : ", aList.pop(-1))
print("Updated List:")
print(aList)

執行上面的程式後,輸出如下:

Popped Element :  876
Updated List:
[123, 456, 789]

示例

但是,如果傳遞給方法的索引大於列表的長度,則會引發 IndexError。

aList = [1, 2, 3, 4]
print("Popped Element : ", aList.pop(5))
print("Updated List:")
print(aList)

讓我們編譯並執行給定的程式,以產生以下結果:

Traceback (most recent call last):
  File "main.py", line 2, in 
    print("Popped Element : ", aList.pop(5))
IndexError: pop index out of range
python_lists.htm
廣告