Python Delete Variable

Learn how to delete a variable in Python using del, what happens after deleting a variable, how to clear variables, unset names, and whether del frees memory immediately.

Published

Updated

Read time 7 min read

Reviewed byDeepak Prasad

Python Delete Variable

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.

python
name = "Alice"
del name
try:
    print(name)
except NameError as exc:
    print(exc)
Output

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.

python
count = 10
print("before:", count)
del count
try:
    print(count)
except NameError:
    print("after: count is not a name anymore")
Output

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.

python
a, b, c = 1, 2, 3
del a, b, c
try:
    print(a)
except NameError:
    print("all three names removed")
Output

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
python
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")
Output

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.

python
data = [1, 2, 3]
backup = data
del data
print(backup)
Output

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.

python
value = 100
del globals()["value"]
try:
    print(value)
except NameError:
    print("global name value is gone")
Output

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.

python
x = 1
print(any(n == "x" for n in dir()))
Output

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.

python
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"))
Output

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 x always frees memory immediately—other references may keep the object alive.
  • Using x after del x without reassigning—expect NameError.
  • Bulk-deleting globals based on dir() output—easy to break notebooks and libraries.
  • Treating x = None the same as del x—the name still exists in the first case.
  • Confusing items.clear() with del 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 del to “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.


References


Frequently Asked Questions

1. Does del in Python free memory right away?

del removes a name binding; the object may live on if another reference exists, and CPython can reclaim it when reference counting drops to zero—the garbage collector module supplements that for cycles, as described in the official gc documentation.

2. What is the difference between del x and x = None?

del x removes the name x from the namespace so a later read raises NameError; x = None keeps the name but points it at the None object instead of your old value.

3. Is it safe to delete every name from globals() using dir() in a loop?

Usually no—dir() only lists names and looping deletes can remove objects your runtime, notebook, or libraries still expect; use del on specific names or refactor scope instead of bulk globals surgery.

4. Can del remove part of a list or dict?

Yes—del items[i] removes an index, del data[key] removes a key, and del obj.attr removes an attribute binding when the object allows it, per the Python tutorial section on del.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …