Python pop 函数用于从现有列表中移除用户指定索引处的元素。在本节中,我们将通过实际示例讨论如何使用它,pop 列表方法的语法是:
listname.pop(index_value)
请记住,索引位置从 0 开始,到 n-1 结束。
Python List pop 示例
它会移除指定索引处的元素并显示该元素。移除后,剩余的值会向上移动以填补索引的空隙。如果我们知道索引值并想查看已删除的值,可以使用此列表 pop 函数来移除该项。
下面的代码移除了索引位置为 1 和 2 的元素。您可以将已移除的值赋给新变量来显示它。例如,第一个 b,返回 20。
a = [10, 20, 30, 40] print(a) b = a.pop(1) print(b) print(a) a.pop(2) print(a)
[10, 20, 30, 40]
20
[10, 30, 40]
[10, 30]
Python pop 第一、第二个列表项
在此示例中,我们声明了一个字符串列表。接下来,我们使用该方法移除了索引位置为 1 和 2 的元素。

提示:有关 Python 和 函数 的所有信息,请参阅 List 文章。
这是该列表 pop 方法在字符串上删除元素的另一个示例。
Fruits = ['Apple', 'Orange', 'Grape', 'Banana']
Fruit = Fruits.pop(1)
print(Fruits)
print('Item extracted = ', Fruit)
print('========')
Fruit = Fruits.pop(1)
print(Fruits)
print('Item extracted = ', Fruit)
print('========')
Fruit = Fruits.pop(1)
print(Fruits)
print('Item extracted = ', Fruit)
print('========')
['Apple', 'Grape', 'Banana']
Item extracted = Orange
========
['Apple', 'Banana']
Item extracted = Grape
========
['Apple']
Item extracted = Banana
========
如何 pop 混合列表项?
我将在此函数上使用 Mixed。在这里,我们声明了一个包含数字和单词的混合列表。接下来,我们使用 pop 函数移除了索引为 2 的元素。
MixFr = ['apple', 1, 'Orange', 5, 'Kiwi', 'Mango'] print(MixFr) MixFr.pop(2) print(MixFr)
['apple', 1, 'Orange', 5, 'Kiwi', 'Mango']
['apple', 'Orange', 'Kiwi', 'Mango']
如何 pop 嵌套列表项?
此程序会删除索引位置为 2 和 3 的嵌套项。
Nested = [[71, 222], [22, 13], [11, 22], [44, 55], [99, 77]] print(Nested) Nested.pop(2) print(Nested) Nested.pop(3) print(Nested)
[[71, 222], [22, 13], [11, 22], [44, 55], [99, 77]]
[[71, 222], [22, 13], [44, 55], [99, 77]]
[[71, 222], [22, 13], [44, 55]]