列出 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 remove()用法及代碼示例
- Python List clear()用法及代碼示例
- Python List index()用法及代碼示例
- Python List sort()用法及代碼示例
- Python List count()用法及代碼示例
- Python List reverse()用法及代碼示例
- Python List copy()用法及代碼示例
- Python List extend()用法及代碼示例
- Python Lock acquire()用法及代碼示例
- Python Lock release()用法及代碼示例
- Python Lock locked()用法及代碼示例
- Python numpy.less()用法及代碼示例
- Python Sympy Permutation.list()用法及代碼示例
- Python Matplotlib.figure.Figure.subplots_adjust()用法及代碼示例
- Python numpy.tril()用法及代碼示例
- Python Matplotlib.pyplot.matshow()用法及代碼示例
- Python __file__用法及代碼示例
- Python Pandas Panel.add()用法及代碼示例
- Python Matplotlib.axis.Tick.get_window_extent()用法及代碼示例
- Python numpy.fromstring()用法及代碼示例
注:本文由純淨天空篩選整理自 Python List pop() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。