Python 中 pop 函数移除并返回指定索引处的元素,如果未指定索引,则移除并返回最后一个元素。

Python 中 pop 的含义
Python 中的 pop 函数用于移除并返回指定索引处的元素,如果未指定索引,则移除并返回最后一个元素。
语法
<code class="python">pop(index=-1)</code>
参数
立即学习“Python免费学习笔记(深入)”;
- index (可选):要移除元素的索引。
返回值
- 移除的元素。
用法
以下示例演示了 pop 函数的用法:
<code class="python"># 创建一个列表
fruits = ['apple', 'banana', 'cherry', 'durian']
# 使用索引移除元素
removed_fruit = fruits.pop(2)
# 使用默认索引移除最后一个元素
removed_last_fruit = fruits.pop()
# 输出移除的元素
print("Removed fruit:", removed_fruit)
print("Removed last fruit:", removed_last_fruit)</code>输出
<code>Removed fruit: cherry Removed last fruit: durian</code>
在上面的示例中:
- 使用索引 2 移除元素 "cherry"。
- 使用默认索引 (-1) 移除最后一个元素 "durian"。



















