带有示例的Python列表pop()方法

清单pop()方法

pop()方法用于从列表中删除指定索引/位置处的元素,此方法与该列表(我们必须从中删除元素的列表)一起调用,索引作为参数提供。

语法:

    list_name.pop(index)

Parameter(s):

  • index –这是一个可选参数,它表示列表中的索引,我们必须删除该元素。如果我们不提供该值,那么它的默认值将是-1,代表最后一项。

返回值:

此方法的返回类型是元素的类型,它返回移除的元素。

范例1:

# 带有示例的Python列表pop()方法

# 宣布名单
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]

# 打印清单
print("cars before pop operations...")
print("cars: ", cars)

# 从第二个索引中删除元素
x = cars.pop(2)
print(x,"is removed")

# 从第0个索引中删除元素
x = cars.pop(0)
print(x,"is removed")

# 打印清单 
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列表pop()方法

# 宣布名单
x = [10, 20, 30, 40, 50, 60, 70]

# 打印清单
print("x before pop operations...")
print("x: ", x)

res = x.pop(0)   # 将删除第0个元素
print(res,"is removed")

res = x.pop()   # 将删除最后一个元素
print(res,"is removed")

res = x.pop(-1)   # 将删除最后一个元素
print(res,"is removed")

# 打印清单
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列表pop()方法

# 宣布名单
x = [10, 20, 30, 40, 50, 60, 70]

# 打印清单
print("x before pop operations...")
print("x: ", x)

res = x.pop(15) # 将返回错误
print(res," is removed")

# 打印清单
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) # 将返回错误
IndexError: pop index out of range