當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python List pop()用法及代碼示例


列出 pop() 方法

pop() 方法用於從列表中刪除指定索引/位置處的元素,使用此列表(我們必須從中刪除元素的列表)調用該方法,並將索引作為參數提供。

用法:

    list_name.pop(index)

參數:

  • index– 它是一個可選參數,它表示列表中的索引,我們必須刪除該元素。如果我們不提供該值,則默認值為 -1,表示最後一項。

返回值:

這個方法的返回類型是元素的類型,它返回被移除的元素。

範例1:

# Python List pop() Method with Example

# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]

# printing the list
print("cars before pop operations...")
print("cars:", cars)

# removing element from 2nd index
x = cars.pop(2)
print(x,"is removed")

# removing element from 0th index
x = cars.pop(0)
print(x,"is removed")

# printing the list 
print("cars before pop operations...")
print("cars:", cars)

輸出

cars before pop operations...
cars: ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
Audi is removed
BMW is removed
cars before pop operations...
cars: ['Porsche', 'Lexus', 'Audi']

範例2:

# Python List pop() Method with Example

# declaring the list
x = [10, 20, 30, 40, 50, 60, 70]

# printing the list
print("x before pop operations...")
print("x:", x)

res = x.pop(0)   # will remove 0th element
print(res,"is removed")

res = x.pop()   # will remove last element
print(res,"is removed")

res = x.pop(-1)   # will remove last element
print(res,"is removed")

# printing the list
print("x after pop operations...")
print("x:", x)

輸出

x before pop operations...
x: [10, 20, 30, 40, 50, 60, 70]
10 is removed
70 is removed
60 is removed
x after pop operations...
x: [20, 30, 40, 50]

如果索引超出範圍,"IndexError" 將返回。

範例3:

# Python List pop() Method with Example

# declaring the list
x = [10, 20, 30, 40, 50, 60, 70]

# printing the list
print("x before pop operations...")
print("x:", x)

res = x.pop(15) # will return an error
print(res," is removed")

# printing the list
print("x after pop operations...")
print("x:", x)

輸出

x before pop operations...
x: [10, 20, 30, 40, 50, 60, 70]
Traceback (most recent call last):
  File "main.py", line 10, in <module>
    res = x.pop(15) # will return an error
IndexError:pop index out of range


相關用法


注:本文由純淨天空篩選整理自 Python List pop() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。