当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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