在Python中,`pop`函数用于移除并返回列表中指定索引处的元素。如果未指定索引,则默认移除并返回列表中的最后一个元素。`pop`函数会修改原始列表。
创建一个列表
fruits = ['apple', 'banana', 'cherry', 'durian']
使用索引移除元素
removed_fruit = fruits.pop(2) 移除索引为2的元素,即'cherry'
使用默认索引移除最后一个元素
removed_last_fruit = fruits.pop() 移除并返回最后一个元素,即'durian'
输出移除的元素
print("Removed fruit:", removed_fruit)
print("Removed last fruit:", removed_last_fruit)
输出结果将会是:
Removed fruit: cherry
Removed last fruit: durian
需要注意的是,`pop`函数也可以用于字典,此时它会删除指定键并返回对应的值。如果不指定键或者指定的键不存在,可以提供一个默认值来避免`KeyError`异常。