pop() 与 del 在 Python 中:相同结果,却完全不同的意图

发布: (2026年2月26日 GMT+8 23:13)
3 分钟阅读
原文: Dev.to

Source: Dev.to

.pop() 与 del 在 Python 中的对决 — 百万美元的问题 💰

实际情况是,两者都可以从列表中删除元素,但它们的使用理念不同。

牢记:

  • .pop() → 📨 送货员 – 从列表中删除元素 并把它交给你 使用。
  • del → 🔥 碎纸机 – 从列表中删除元素 并将其销毁。你得不到该值。

.pop() 场景(最常见)

场景

你正在处理一堆任务或一副牌。你删除该元素是因为需要使用它的值。

tasks = ["Wash dishes", "Study SQL", "Sleep"]

# pop() removes the last item and RETURNS it
current_task = tasks.pop()

print(f"I'm working on: {current_task}")
# Output: I'm working on: Sleep

print(tasks)
# Output: ['Wash dishes', 'Study SQL']

🔎 注意: 如果你没有把结果赋给变量,"Sleep" 仍然会被删除。pop() 的核心目的通常是使用被删除的值。

del 场景(外科手术式删除)

场景

你想按索引删除特定的东西,并且不在乎它的值。你只想把它移除。

users = ["Admin", "Felipe", "Malicious_Hacker", "Guest"]

# I know the hacker is at index 2.
# I don’t need the value — I just want it removed.
del users[2]

print(users)
# Output: ['Admin', 'Felipe', 'Guest']

del 在需要删除元素而不取回它们时更为得心应手。pop() 每次只能删除 一个 元素,而 del 可以一次删除列表的整个切片:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Remove from index 2 up to (but not including) 5
del numbers[2:5]

print(numbers)
# Output: [0, 1, 5, 6, 7, 8, 9]

pop() 实现相同操作则需要循环或多次调用。

pop() 实际上是怎么工作的

考虑手动的两步操作:

x = p1[len(p1) - 1]   # Step 1: copy the value
del p1[len(p1) - 1]   # Step 2: delete it

这基本上就是 pop() 在内部的实现方式——只用一行代码:

x = p1.pop()   # Copies and removes at the same time

对比

操作是否返回值?删除方式是否删除切片?典型使用场景
list.pop(i)✅ 是索引(默认:最后)❌ 否栈、队列、元素处理
del list[i]❌ 否索引✅ 是数据清理、删除范围
list.remove(x)❌ 否值("Felipe"❌ 否当你不知道索引时
0 浏览
Back to Blog

相关文章

阅读更多 »

必须了解的数组方法

变异方法会更改原数组 - push – 在末尾添加 - pop – 删除末尾元素 - shift – 删除开头元素 - unshift – 在开头添加 所有这些都不会返回新的数组,而是直接修改原数组。