If you want to drop a name you no longer need, reset a container without losing the container itself, or understand why memory did not shrink the second you typed del, this page walks you through del, what it really does to names versus objects, and the patterns people confuse with “clear.” I keep globals() for the rare dynamic case and warn you off “delete everything from dir()” tricks that break notebooks and apps.
In Python, a variable is just a name bound to an object; del removes that binding from the current namespace. Nothing here moves data to a trash folder—it only unties names from values.
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
Can you delete a variable in Python?
Yes. You remove the name with del, and any later use of that name raises NameError because the binding is gone.
name = "Alice"
del name
try:
print(name)
except NameError as exc:
print(exc)You should see a NameError message like name 'name' is not defined. That is the direct answer most readers are looking for: del removed the name name from this scope, not “the string Alice” as a magical global delete.
Delete a variable using del
del is a statement, not a function call—you write del x, not del(x) (the latter is a different syntax edge case beginners hit). It unbinds one or more names from the local or global namespace you are executing in.
count = 10
print("before:", count)
del count
try:
print(count)
except NameError:
print("after: count is not a name anymore")You should see before: 10 then the message that count is gone.
What happens after deleting a variable?
After del x, the name x no longer exists in that scope. If you assign to x again later, you simply create a fresh binding—Python does not remember the old one.
If another part of the code still holds a reference to the same object under a different name, that object is still there; you only removed one label.
Delete multiple variables using del
You can list several targets in one del statement, separated by commas.
a, b, c = 1, 2, 3
del a, b, c
try:
print(a)
except NameError:
print("all three names removed")You should see all three names removed.
Clear variable vs delete variable
“Clear” usually means change the value or empty a container while keeping the same name or the same object. del removes a name from the namespace, or removes part of a mapping or sequence when you use subscripts.
| Action | Example | What it means for you |
|---|---|---|
| Delete a name | del x |
Name goes away; later reads raise NameError |
| Keep name, drop old reference | x = None |
Same name now points at None (see Python None examples) |
| Empty a list in place | items.clear() |
Same list object, length becomes zero |
| Empty a dict in place | data.clear() |
Same dict object, all keys removed |
| Rebind to a new empty list | items = [] |
Name now points at a brand-new list |
items = [1, 2, 3]
items.clear()
print(items)
items = [1, 2, 3]
del items
try:
print(items)
except NameError:
print("del removed the name items, not just the contents")You should first see [] from clear, then the message about del removing the name itself.
Delete variable from memory in Python
del removes a reference—it does not promise to reclaim memory immediately in a way you can measure from your code. In CPython, objects use reference counting: when the last reference goes away, the object can be destroyed right away. If another variable, container slot, closure cell, or attribute still points at the same object, it stays alive.
The gc module documents the cycle-detecting collector that supplements reference counting when objects refer to each other in a loop.
data = [1, 2, 3]
backup = data
del data
print(backup)You should still see [1, 2, 3]. You deleted the name data, not the list object, because backup still references it.
Delete global variable using globals()
Inside a module or interactive session, global names live in a dict returned by globals(). You can delete a global by string key when you truly build names dynamically—otherwise prefer plain del value for readability. For how globals are created and scoped, see global variables in Python.
value = 100
del globals()["value"]
try:
print(value)
except NameError:
print("global name value is gone")You should see global name value is gone. Treat dynamic deletion as advanced: typos in the string key, accidental removal of names other code expects, and harder debugging all get worse when you lean on this pattern everywhere.
Should you delete all variables using dir()?
Usually, no. dir() without arguments lists names in the current scope; it does not delete anything by itself. Some old snippets loop for name in dir(): del globals()[name] while skipping __ prefixes—that can still remove names your environment, framework, or notebook kernel relies on and is not a pattern I would ship.
If you need a clean slate in a REPL, restart the interpreter or kernel. In application code, delete specific names you own or refactor so fewer globals exist in the first place.
x = 1
print(any(n == "x" for n in dir()))You should see True, showing dir() is only introspection here—not a bulk delete tool.
Delete list item, dictionary key, or object attribute using del
The same del statement can target part of an object: indices, slices, keys, or attributes, as covered in the Python tutorial on del. To remove dictionary keys specifically, see remove a key from a Python dictionary.
items = ["a", "b", "c"]
del items[1]
print(items)
user = {"name": "Alice", "age": 30}
del user["age"]
print(user)
class Box:
def __init__(self):
self.tag = "old"
box = Box()
del box.tag
print(hasattr(box, "tag"))You should see ['a', 'c'], then {'name': 'Alice'}, then False because the attribute binding is gone.
Common mistakes when deleting variables in Python
- Assuming
del xalways frees memory immediately—other references may keep the object alive. - Using
xafterdel xwithout reassigning—expectNameError. - Bulk-deleting globals based on
dir()output—easy to break notebooks and libraries. - Treating
x = Nonethe same asdel x—the name still exists in the first case. - Confusing
items.clear()withdel items—first empties the list object, second removes the variable name. - Deleting a name something else still needs later in the same function—control flow and closures can surprise you.
- Expecting
delto “delete the object everywhere”—only each binding matters; other aliases keep it reachable.
Python delete variable quick reference table
| Need | What to write |
|---|---|
| Remove a name | del x |
| Remove several names | del x, y, z |
| Keep name, drop value | x = None |
| Empty list in place | items.clear() |
| Empty dict in place | data.clear() |
| Remove list index | del items[i] |
| Remove dict key | del data[key] |
| Remove attribute | del obj.attr |
| Remove global by string key | del globals()["name"] (use sparingly) |
| Force cycle collection | Usually avoid; rarely import gc; gc.collect() after you understand cycles |
Summary
You can delete a variable in Python with del name, which removes the binding so the name disappears from that scope. That is different from clearing a container or setting a name to None, and it does not automatically destroy the underlying object while other references exist. Use del on indices, keys, or attributes when you need to remove part of an object, use globals() lookups only for genuine dynamic cases, and avoid mass deletion driven by dir() in real programs—reach for smaller scopes or a fresh interpreter when you need a clean slate.

