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") | ❌ 否 | 当你不知道索引时 |