列出 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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。