How to Delete a Variable in Python (and When It Frees Memory)

How To Delete A Variable In Python?

Do you know ‘How to delete a variable in Python?’ Well, let’s discuss the Python delete variable & ways to clear Python variables.

Deleting one takes a single word. We write del followed by the variable name, like del zap, and after that line, the name ‘zap’ does not exist anymore. But there is a second question hiding behind the first one: when we delete a variable, does Python really give the memory back? Sometimes it does, and sometimes it does not. In this article, we will measure it with real numbers so you can see when it does and when it does not.

Let’s discuss more about deleting a Python variable with the help of code implementation. That will help to clear the topic in a better manner.

What Is One Unique Feature Of Python Variable?

Python Variables are generally different from other traditional variables in any programming language. In Python, every value is treated as an object, and a variable is only a name that refers to that object. That means the Python variable works as the reference or the pointer to the actual data.

This is the reason, we don’t need to declare the data type of any variable before assigning any values to it. The type belongs to the value, not to the name. To understand how Python handles different types of values, explore our guide on Different Kinds of Python Data Types.

So, you might be getting the difference between normal variables of other programming languages & Python variables. An easy way to picture it is a name tag tied to a box with a string. The box is the value. The tag is the variable. Keep this picture in mind, because deleting a variable in Python means cutting the string, not destroying the box.

How Variable Is Stored In Python?

Now, we have the basic information related to the variables in Python. Before we move to the deleting process, we should understand the storing process of the variables in Python.

In Python, the storing of the variable goes differently. The names are kept in one place, which Python calls a namespace. You can think of it as a table of names. The values associated with those names are stored as objects in another area of memory, called the heap. Each name in the table simply points to its object.

Single Connection Variable Stored

Suppose, another variable is assigned from the first one, like one = zap. Then that new variable will refer to the same value in the heap. There is no need to create a new value for it. Now, two name tags are tied to one box.

Double Connection Variable Stored

We can check this ourselves. Python has an id() function that tells us which object a name points to. Let us use it to check, and then delete one of the two names.

zap = [10, 20, 30]   # One List, One Name
one = zap            # Second Name For The Same List

print(id(zap) == id(one))   # Do Both Names Point To The Same Object?

del zap              # Deleting The First Name

print(one)           # The List Is Still Alive Through The Second Name

Output:

True
[10, 20, 30]

The first line of the output is True, so both names were pointing to the same list. Then we deleted ‘zap’. But the list did not go anywhere. We can still print it through the name ‘one’. We cut one string, and the box is still held by the other string.

Remember this small program for the rest of the article. The del keyword removes a name. It does not directly remove a value.

Why Delete Variable Python Is Important In Terms Of Memory Management?

Delete variables in Python is useful for two reasons. One is memory management & the other is keeping our program clean. Both things might look similar, but there is a difference between them.

Free Value

The variable concept in Python program is different & if a large value is not released after use, it will occupy some space in memory for as long as a name is tied to it. When the last name is removed, the value becomes free, as the picture above shows, and Python takes that memory back. This cleaning-up is what people call Garbage Collection.

Here, we should clear up one common fear. Garbage Collection never removes data that we are still using. It only takes back a value that our program has no way left to reach. So, it cannot remove some important data behind our back.

Then, when does deleting really matter? Let us be practical about it.

  • For a small homework program, it does not matter. Python frees everything when the program ends. We do not need to delete each variable.
  • For large data, it matters. If we load a file with a few million rows, make a cleaned copy, and keep both, we are holding the data twice. Deleting the one we no longer need can be the difference between a program that runs and a program that stops with a MemoryError.
  • In a Jupyter Notebook, it matters. Variables stay alive until the notebook is restarted, even if we made them an hour ago in a cell we have forgotten.
  • For clean code, it sometimes matters. Removing a temporary name makes sure we do not use an old value by mistake later in the program.

How To Delete A Variable From Memory In Python?

Now, it is time to discuss the core concept of this article. Here, we will demonstrate some methods that can be useful to remove variables from Python. We will start with very simple methods that can be used on any normal variable.

Later, we will move towards the demonstration of other variable removal processes that can be utilized on other complex elements. But for the time being, let us start with the very basic one.

Using The Del Keyword:

For performing delete variable python, there is a special operation that is already available. There is no need to use any user-defined method. It is already built into the language. This is known as del. You will often see it written as del(), but del is not a function. It is a keyword, like if or for.

But still, it can be written like a function, with parentheses, and Python accepts it. Simply, programmers need to give the variable names after it. Then those names will be removed.

General Syntax: del variable-name or del(variable-name)

Code Example To Delete A Variable In Python:

Coding, Zap, One = 20, 30, 10 # Declaration Of Variables

print("Coding: ", Coding, " Zap: ", Zap, " One: ", One) # Normal Printing

del Coding, Zap, One # Deleting Variables

print("Coding: ", Coding, " Zap: ", Zap, " One: ", One) # Again Printing Values

Steps Of The Program:

  • Declare some random variables & provide value to them.
  • Print the data on the screen.
  • Use the del keyword & provide the names of the variables that should be deleted. We can delete several names in one line by separating them with commas.
  • Now, again try to print the variable data.

The steps mentioned above demonstrate how you can delete variables in Python using the del keyword. Let us try to find out the output of the above code. It will help to understand the way to delete a variable in Python using del.

Output:

Coding:  20  Zap:  30  One:  10
Traceback (most recent call last):
  File "del_basic.py", line 7, in <module>
    print("Coding: ", Coding, " Zap: ", Zap, " One: ", One) # Again Printing Values
                      ^^^^^^
NameError: name 'Coding' is not defined

We can see that the printing operation before deleting the variables works properly, but later it is giving an error. We have used del, which deleted all the variables. Now, we are trying to print those values that are deleted. So, the error is coming.

The error is called a NameError, and its message is "name 'Coding' is not defined." Python is telling us that it has no such name in its table now. If you meet this error in your own program without ever using del, it usually means a spelling mistake in the variable name. Our guide on common Python errors covers that case.

Using Dir() & Globals() Functions:

The dir() & globals() are two functions that can also help to delete variables in Python programs. But the implementation is not as easy as the previous one. Here, the process of deleting elements is quite tricky.

The simple use of the dir() function is not going to delete any element from the programs. The dir() function will provide the list of names present in the program, both the built-in ones and the ones we made. It helps to filter what we want to delete from one program.

zap = 2023 # Declaration Of Variable
print(dir()) # Printing All The Names Python Knows In This Program

Output:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'zap']

If the above program is executed, we will get the built-in names that start and end with the double underscore (__), and at the end of the list, our own variable ‘zap’.

Nothing will be deleted with the use of the dir() function alone. With the dir() function, one should use the globals() function as well. The globals() function gives us the table of global names as a dictionary, and we can delete a name from that dictionary. Using these two together will help to delete our own variables in one go.

Code To Execute The Dir() & Globals() Functions:

zap = 2023 # Declaration Of Variable
one = dir() # Using dir() function & Making A List

for a in one: # Defining One Loop To Check
    if not a.startswith('__'): # Filtering The Inbuilt Variables With Underscore
        del globals()[a] # Deleting Global Variables

print(zap) # Try To Print The Old Variable

Steps Of The Program:

  • Declare some variables inside of the program along with some values.
  • Now, the dir() function will be used, and its list of names will be saved in one variable.
  • Now, one for loop will be implemented that will check the elements of that list. If the element is not starting with the underscore (__), it will be caught & deleted using globals().
  • Now, again we will try to print any of the elements & find the error message.

Let us try to find out the output of the above code. It will help to understand the way to delete variable Python using the dir() & globals() function.

Output:

Traceback (most recent call last):
  File "dir_globals.py", line 8, in <module>
    print(zap) # Try To Print The Old Variable
          ^^^
NameError: name 'zap' is not defined. Did you mean: 'map'?

In the output, we can see that the variables are deleted successfully with the help of those two functions. It is giving an error message because the variable is now deleted.

A word of caution about this method. It deletes every name that does not start with an underscore. That includes the modules we imported and the functions we wrote, not only the variables. If we run it in the middle of a program, the lines after it may stop working. It also leaves its own two helper names, ‘one’ and ‘a’, behind. And never run it inside a Jupyter Notebook, because there it also deletes names that the notebook itself needs. So, use it only when you truly want to wipe a script clean, and prefer the plain del for everything else.

Does Del Really Free The Memory? Let Us Measure It

We saw earlier that del removes a name and not a value. So, what happens to the memory? Python has a module named tracemalloc that reports how much memory our program is using at any moment. We used it to run three small tests. In each one, we build a list of one million numbers, which is big enough to see clearly.

Test 1: The value has only one name.

import tracemalloc

tracemalloc.start()

data = list(range(1_000_000))   # A List Of One Million Numbers
used, _ = tracemalloc.get_traced_memory()
print("With The List:   ", round(used / 1_000_000, 1), "MB")

del data                        # The Only Name Is Deleted
used, _ = tracemalloc.get_traced_memory()
print("After del:       ", round(used / 1_000_000, 1), "MB")

Output:

With The List:    40.0 MB
After del:        0.0 MB

The list took about 40 MB. After del, the usage came back to zero. This is the simple case. The list had one name, we removed it, nothing else was holding the list, and Python released the memory at once.

Test 2: The value has two names.

import tracemalloc

tracemalloc.start()

data = list(range(1_000_000))   # A List Of One Million Numbers
backup = data                   # A Second Name For The Same List
used, _ = tracemalloc.get_traced_memory()
print("With The List:        ", round(used / 1_000_000, 1), "MB")

del data                        # One Name Is Deleted, One Is Left
used, _ = tracemalloc.get_traced_memory()
print("After del data:       ", round(used / 1_000_000, 1), "MB")

del backup                      # Now The Last Name Is Gone
used, _ = tracemalloc.get_traced_memory()
print("After del backup:     ", round(used / 1_000_000, 1), "MB")

Output:

With The List:         40.0 MB
After del data:        40.0 MB
After del backup:      0.0 MB

This is the surprising case. We deleted ‘data’, and the memory did not go down at all. The reason is the second name, ‘backup’. As long as one name is still tied to the list, the list stays. Only when we deleted ‘backup’ too did the 40 MB come back.

So, if you delete a big variable and your program is still using a lot of memory, look for another name that refers to the same value. It may be a second variable, an element inside a list or dictionary, or an attribute of some object.

Test 3: Two values that point to each other.

There is one more special case. Suppose two lists hold each other, like a circle. Even after we delete both names, each list is still referred to by the other one. Python has a separate helper for this, which is the garbage collector in the gc module. Normally, it runs on its own from time to time. In this test, we switched it off for a moment so that we can see what it does.

import gc
import tracemalloc

gc.disable()                    # Switched Off Only To Make The Effect Visible
tracemalloc.start()

first = list(range(1_000_000))
second = [first]                # second Holds first
first.append(second)            # And first Holds second: A Circle

used, _ = tracemalloc.get_traced_memory()
print("With The Two Lists:   ", round(used / 1_000_000, 1), "MB")

del first, second               # Both Names Are Deleted
used, _ = tracemalloc.get_traced_memory()
print("After del:            ", round(used / 1_000_000, 1), "MB")

gc.collect()                    # Asking The Garbage Collector To Clean Up
used, _ = tracemalloc.get_traced_memory()
print("After gc.collect():   ", round(used / 1_000_000, 1), "MB")

Output:

With The Two Lists:    41.0 MB
After del:             41.0 MB
After gc.collect():    0.0 MB

After del, the memory was still in use, because of the circle. After gc.collect(), it was released. (The reading is 41 MB here and not 40 because the append made the first list grow a little.) In your normal programs, the collector is switched on, and it will find such circles by itself after some time. If you want it to happen right away, for example after deleting a very large object, you can write import gc and call gc.collect() yourself.

Put the three tests together, and the rule is short. Writing del gives the memory back only when it removes the last reference to the value.

Del, None, Or Clear(): Which One Should We Use?

"Python clear variable" is a common search when someone wants to empty a variable. Python has three different things that sound alike, and they do not behave alike. In the following program, we try all three on a list that has two names, ‘zap’ and ‘one’.

# Case 1: del Removes The Name
zap = [1, 2, 3]
one = zap
del zap
print("After del:     one =", one)

# Case 2: None Keeps The Name, But It Now Points To None
zap = [1, 2, 3]
one = zap
zap = None
print("After None:    zap =", zap, "| one =", one)

# Case 3: clear() Empties The List Itself, For Every Name That Uses It
zap = [1, 2, 3]
one = zap
zap.clear()
print("After clear(): zap =", zap, "| one =", one)

Output:

After del:     one = [1, 2, 3]
After None:    zap = None | one = [1, 2, 3]
After clear(): zap = [] | one = []

The three lines of the output tell three different stories:

  • del zap removes the name ‘zap’. The other name still has the full list. Using ‘zap’ after this gives a NameError.
  • zap = None keeps the name ‘zap’, but ties it to the special value None. The other name still has the full list. Using ‘zap’ after this gives no error. It simply prints None.
  • zap.clear() does not touch the names at all. It empties the list itself. As both names refer to the same list, both of them now show an empty list.

So, which one should we use? If the name should not be used again, use del. If the name will be used again later and we want to mark it as "nothing here yet," use None. If other parts of the program share the same list and all of them should see it empty, use clear().

How To Delete A Variable Only If It Exists?

If we use del on a name that is not there, Python stops with a NameError. This happens a lot when the same cleanup code runs twice. There are two simple ways to avoid it. We can check for the name first, or we can try the deletion and catch the error. The first way, with globals(), is for global variables. The second way works everywhere.

zap = 2023

# Way 1: Check First
if "zap" in globals():
    del zap
    print("zap Was Deleted")

# Way 2: Try, And Catch The Error If The Name Is Not There
try:
    del zap
except NameError:
    print("zap Does Not Exist, Nothing To Delete")

Output:

zap Was Deleted
zap Does Not Exist, Nothing To Delete

Do We Need To Delete Variables Inside A Function?

Usually, no. A variable that is created inside a function is a local variable. It lives only while the function is running. When the function ends, Python removes all of its local names on its own.

def codingzap():
    temp = [1, 2, 3]            # A Local Variable
    print("Inside:", temp)
    # No del Needed: temp Is Removed When The Function Ends

codingzap()
print(temp)                     # temp Does Not Exist Out Here

Output:

Inside: [1, 2, 3]
Traceback (most recent call last):
  File "function.py", line 7, in <module>
    print(temp)                     # temp Does Not Exist Out Here
          ^^^^
NameError: name 'temp' is not defined

We never wrote del, and still ‘temp’ is gone once the function has finished. This is a good reason to keep big temporary values inside functions. They clean up after themselves.

One thing does not work the way it looks like it should. We cannot delete a global variable from inside a function by simply writing del. Python reads the name as a local one, finds nothing, and gives an error that looks strange at first:

zap = 2023                      # A Global Variable

def codingzap():
    del zap                     # Trying To Delete The Global From Inside

codingzap()

Output:

Traceback (most recent call last):
  File "unbound.py", line 6, in <module>
    codingzap()
  File "unbound.py", line 4, in codingzap
    del zap                     # Trying To Delete The Global From Inside
        ^^^
UnboundLocalError: cannot access local variable 'zap' where it is not associated with a value

To delete the global variable from inside the function, we have to add the line global zap before the del line. With that one extra line, the program runs without any error, and the name is removed from the global table.

Now, after knowing the methods required for deleting any Python variable, it is time to move towards a bit more advanced topic. In this case, we will discuss the deleting process of other kinds of variables and instances in Python. So, let us start our journey!

How To Delete Instance Variable In Python?

Instance variables are a special feature of any Python program. Instance variables are those elements that are associated with any object or instance in any class of Python program. And such variables are only associated with one instance, not more than one.

Suppose, in any car object, you want to put some ID numbers there. So, the ID numbers should be different in each case. In this case, the ID number will be the Instance Variable of that object. And fortunately, the ‘del’ keyword is efficient enough to remove any instance variable.

General Syntax: del instance-name.variable-name

Code to use Del Keyword to delete Instance Variable in Python:

class CodingZap: # Declaring The Class 
    def __init__(self, value):
        self.pe = value

zap = CodingZap("Connect CodingZap!") # Creating Instances
print(zap.pe) # Printing The Variable
del zap.pe # Deleting The Instance Variable
print(zap.pe)  # It Will Raise AttributeError

Steps Of The Program:

  • First, declare a class where a value will be assigned to a self-variable.
  • Now, an instance will be created using some statement which will act as the value.
  • Now, using the above syntax delete the instance variable.
  • Again, try to access the instance variable. As the variable is now deleted, it will flag the Attribute Error.

Output:

Connect CodingZap!
Traceback (most recent call last):
  File "instance.py", line 8, in <module>
    print(zap.pe)  # It Will Raise AttributeError
          ^^^^^^
AttributeError: 'CodingZap' object has no attribute 'pe'

From the above output, we can see that the first print statement is executed correctly. But, later when the instance variable gets deleted, it is prompting the Attribute Error to the code. Hence, the operation is successful here.

Notice that the error is an AttributeError this time, not a NameError. The object ‘zap’ still exists. Only its attribute ‘pe’ is gone.

How To Delete A Class Variable In Python?

A class variable is a simple item in every coding language where the class concept is present. We are talking about the Object Oriented Programming concept here. As per the name of the variable, it is a simple variable that is declared inside of any class, and it is shared by all the objects of that class.

Such variables can again be removed from the program after their task is completed. And like every removing problem, we have to use the common solution 'del' keyword again in this case. The syntax of the solution itself says how easy the solution can be.

General Syntax: del class-name.variable-name

Code to demonstrate the process of removal of any class variable in Python:

class CodingZap: # Declaring The Class & Variable
    var = "CodingZap Is The Best!"

print(CodingZap.var) # Printing The Variable
del CodingZap.var # Deleting The Variable
print(CodingZap.var)  # It Will Raise AttributeError

Steps Of The Program:

  • Declare a class and assign some variables there.
  • Now, print the variable value in the program normally.
  • After printing the value, use the above syntax to remove the variable details from the code.
  • Again try to print the variable value. As it is deleted, it will prompt the Attribute Error.

Output:

CodingZap Is The Best!
Traceback (most recent call last):
  File "classvar.py", line 6, in <module>
    print(CodingZap.var)  # It Will Raise AttributeError
          ^^^^^^^^^^^^^
AttributeError: type object 'CodingZap' has no attribute 'var'

The above output clearly shows that the print statement was working the first time when we did not delete the variable. So, the assigning process was correct. Now, after removing it is flagging the error, so the removal process is also completed well.

There is one situation with class variables that often shows up in lab quizzes. What if an object has an instance variable with the same name as the class variable, and we delete it from the object?

class CodingZap:
    var = "Class Value"         # Class Variable, Shared By All Objects

zap = CodingZap()
zap.var = "Instance Value"      # Instance Variable With The Same Name
print(zap.var)

del zap.var                     # Deleting The Instance Variable
print(zap.var)                  # The Class Variable Shows Through Again

Output:

Instance Value
Class Value

There is no error after the del. The instance variable was only covering the class variable. Once it is removed, Python looks one level up, finds the class variable with the same name, and prints that.

How To Delete An Element From List In Python?

The list in Python is considered a special data type that can hold different types of elements. In a single list, one can store an integer, string, float & different other elements without any problem. And in any list, removal of any item is as easy as inserting it there.

And in this case, also, the need to use the keyword ‘del’ becomes necessary. Using the keyword 'del' along with the list name and element index number, you can easily remove any item. Do check the syntax for operating.

General Syntax: del list-name[element-index-number]

Code to define the use of the Del keyword for the removal of list elements in Python:

codingzap = [10, 20, 30, 40] # List of Elements
print("The List Before Removal: ", codingzap) # Printing List
del codingzap[3] # Deleting Elements
print("The List After Removal: ",codingzap) # Printing List

Steps Of The Program:

  • At first, a list will be declared with some values.
  • Now, the list data will be printed in the program normally.
  • Using the above syntax, we will remove any one element from the list.
  • Now, we will again print the list to check the differences.

Output:

The List Before Removal:  [10, 20, 30, 40]
The List After Removal:  [10, 20, 30]

From the above output, we can see that in the first case, the entire list of data is printed. However, after executing the removal statement, the element gets deleted. So if we now try to print the list, the said element will be absent there.

Del vs Remove() vs Pop(), And Deleting From A Dictionary

The del keyword is not the only way to take something out of a list. Lists also have the remove() and pop() methods, and it is easy to mix up the three. The following program uses all of them one after another, and also deletes a key from a dictionary.

codingzap = [10, 20, 30, 40, 50, 60]

del codingzap[1:3]              # Deleting A Slice: Index 1 And 2
print("After del [1:3]:   ", codingzap)

codingzap.remove(50)            # remove() Deletes By Value, Not By Index
print("After remove(50):  ", codingzap)

last = codingzap.pop()          # pop() Deletes And Gives The Value Back
print("After pop():       ", codingzap, "| popped:", last)

prices = {"pen": 2, "notebook": 5, "bag": 30}
del prices["notebook"]          # del Also Works On A Dictionary Key
print("Dictionary:        ", prices)

Output:

After del [1:3]:    [10, 40, 50, 60]
After remove(50):   [10, 40, 60]
After pop():        [10, 40] | popped: 60
Dictionary:         {'pen': 2, 'bag': 30}
  • del works with a position. It can also take a slice and remove several elements at once.
  • remove() works with a value. We tell it what to remove, not where it is.
  • pop() removes the last element (or the one at the index we give) and hands it back to us, so we can store it in a variable.

What Del Cannot Delete

The del keyword can remove an element only from a container that is allowed to change. A tuple and a string are not allowed to change once they are made. If we try, Python refuses.

codingzap = (10, 20, 30) # A Tuple, Not A List
del codingzap[0]

Output:

Traceback (most recent call last):
  File "tuple_err.py", line 2, in <module>
    del codingzap[0]
        ~~~~~~~~~^^^
TypeError: 'tuple' object doesn't support item deletion

We get the same TypeError for a string, with 'str' in place of 'tuple'. We can still delete the whole tuple or string with del codingzap. We just cannot take a single piece out of it.

How To Clear All Variables In Jupyter Notebook Or IPython?

If you write Python in Jupyter Notebook, Google Colab, or Spyder, you are working inside IPython. Here, variables do not go away when a cell finishes. They stay until the kernel is restarted. For this situation, IPython has its own short commands that start with a percent sign. Here is a real session.

In [1]: zap = 2023

In [2]: one = "CodingZap"

In [3]: %who
one    zap

In [4]: %xdel zap

In [5]: %who
one

In [6]: %reset -f

In [7]: %who
Interactive namespace is empty.
  • %who lists the variables we have made so far.
  • %xdel zap deletes one variable and also removes the hidden copies that IPython keeps of earlier results.
  • %reset -f deletes all the variables at once. Without the -f, it first asks for a yes or no.

These commands work only inside IPython and notebooks. In a normal .py file, they are a syntax error, so use del there.

If your notebook still runs out of memory after all this and you cannot work out which variable is holding the data, one of our Python tutors can go through the notebook with you and explain what is keeping it alive.

A One-Page Summary Of Everything Above

What We Want To RemoveWhat To WriteWhat Happens If We Use It Afterward
One variabledel zapNameError
Several variablesdel zap, oneNameError
Empty the name, but keep itzap = NoneNo error, prints None
The contents of a shared listzap.clear()No error, the list is empty
An instance variabledel zap.peAttributeError
A class variabledel CodingZap.varAttributeError
A list element by positiondel codingzap[3]The list is one shorter
A list element by valuecodingzap.remove(50)The list is one shorter
A dictionary keydel prices["notebook"]KeyError for that key
Almost every name in a scriptThe dir() and globals() loopNameError for the deleted names
Every variable in a notebook%reset -fNameError for all of them

Conclusion:

As we saw, it is very important to understand the concept of deleting a variable in Python.

Python deleting variables helps us to work efficiently with problems related to Big Data. We have to use a clear variable Python approach in Data Analytics & more in the future. For small programs, we can leave the cleaning to Python. For large data, remember that del frees memory only when the last reference is gone.

Before going for the delete variable in Python, it is advisable to clear the basics of the Python programming language. As this will help to understand & grab the knowledge in an easy & better way.

So, hope you have liked this piece of article. Share your thoughts in the comments section and let us know if we can improve more.

Frequently Asked Questions

Does del free memory in Python?

Only when it removes the last reference to the value. If another variable, a list, or an object still refers to the same value, the memory stays in use. In our test with a list of one million numbers, the memory came back only after every name for the list was deleted.

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

del x removes the name, so using x afterward gives a NameError. x = None keeps the name and makes it refer to None, so using x afterward gives no error. Both let go of the old value.

How do I clear all variables in Python?

In a Jupyter Notebook or IPython, type %reset -f. In a normal script, loop over dir() and delete every name that does not start with an underscore from globals(). In a script, it is usually simpler to put the code in a function, because local variables are removed when the function ends.

Is del a function in Python?

No. del is a keyword, like if and for. Writing del(x) works only because the parentheses are treated as plain grouping around the name. It is the same as del x.

Do I need to delete variables at the end of my Python program?

No. When a program ends, all of its memory is returned to the computer. Deleting variables is useful in the middle of a long program, or in a notebook that stays open, when a large value is no longer needed.

Why do I get a NameError after using del?

Because the name no longer exists. After del zap, Python has no variable called zap, so any later line that uses it stops with "name 'zap' is not defined." Assign a new value to the name before using it again.