DEV Community

Cover image for pop() vs del in Python: Same Result, Completely Different Intent
Felipe Cezar
Felipe Cezar

Posted on

pop() vs del in Python: Same Result, Completely Different Intent

.pop() vs del in Python — The Million-Dollar Question 💰

In practice, both remove items from a list, but their philosophy of use is different.

To never forget:

  • .pop() → 📨 The Delivery Guy

    It removes the item from the list and hands it to you to use.

  • del → 🔥 The Shredder

    It removes the item from the list and destroys it. You don’t get the value back.


1️⃣ The .pop() Context (Most Common)

Scenario

You’re processing a stack of tasks or a deck of cards.

You remove the item because you need to use its value.

Example

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']
Enter fullscreen mode Exit fullscreen mode

🔎 Note:

If I didn’t assign it to current_task, "Sleep" would still be removed.

But the whole point of pop() is usually to use the removed value.


2️⃣ The del Context (Surgical Removal)

Scenario

You want to delete something specific by index and don’t care about the value.

You just want it gone.

Example

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']
Enter fullscreen mode Exit fullscreen mode

3️⃣ The Crucial Difference: Slicing

This is where del really shines.

pop() removes one item at a time.

del can remove entire slices of a list.

Example

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]
Enter fullscreen mode Exit fullscreen mode

Try doing that with pop() and you’d need a loop or multiple calls.


4️⃣ Under the Hood: What pop() Actually Does

Consider this:

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

That’s effectively what pop() does internally — but in one line:

x = p1.pop()  # Copies and removes at the same time
Enter fullscreen mode Exit fullscreen mode

📌 Quick Summary Table

Command Returns value? Removes by... Removes slices? Typical use case
list.pop(i) ✅ Yes Index (default: last) ❌ No Stacks, queues, processing elements
del list[i] ❌ No Index ✅ Yes Data cleanup, removing ranges
list.remove(x) ❌ No Value ("Felipe") ❌ No When you don’t know the index

Top comments (0)