How to delete or clear variable from memory in Python?

Computer memory is very important not just for storing data, code and instructions but also for the system’s performance. Variables are the simplest and most basic storage units. You must be knowing that Python variables are dynamically typed, i.e, they are declared as and when they are assigned/used.

Sometimes, even though you assigned a variable with some value in the program, you may realize later that that variable is not necessary. In such a scenario, you will want to delete that variable both from your program as well as your memory.
In this tutorial, you will understand how to delete a variable from the memory space in Python.

The del keyword

It is used to simply delete any Python object. (variables,arrays,lists,dictionaries etc).
Syntax: del(element to be deleted)

You can look into the below-coded example to understand this better.

Example 1: Deleting a variable

a=10
print(a)
del(a)
print(a)
10
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-b35d17561a34> in <module>
      2 print(a)
      3 del(a)
----> 4 print(a)

NameError: name 'a' is not defined

Note: The del method can be used not just with variables but with all Python objects like arrays, lists, dictionaries etc.

Example 2: Deleting a list

a=[10,5,9]
print(a)
del(a)
print(a)
[10, 5, 9]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-20675d2b1122> in <module>
      2 print(a)
      3 del(a)
----> 4 print(a)

NameError: name 'a' is not defined

In this case, the program returns a NameError exception. This is because the variable you are trying to access no longer exists in the variable namespace.

However, the above del method only removes the variable from the namespace. It does not remove the variable from the memory space.

Well, so how do we permanently remove the variable and clear its memory?

The gc.collect() method in Python

The del method does not clear the variable from the memory. Hence, to clear the variable from memory you can resort to the gc.collect() method.
The gc.collect() method forces an immediate garbage collection of all generations. You can invoke the garbage collector as demonstrated below.

Example 1: Deleting a variable

import gc
a=10
print(a)
del(a)
gc.collect()
print(a)
10
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-21-a03cb7133a13> in <module>
      4 del(a)
      5 gc.collect()
----> 6 print(a)

NameError: name 'a' is not defined

In this case, you are deleting a from the memory space itself.

Just like the del method, you can invoke the gc.collect()  for clearing the memory of not just variables but for all Python objects.

Example 2: Deleting a dictionary

import gc
a={1:10,2:9,3:8}
print(a)
del(a)
gc.collect()
print(a)
{1: 10, 2: 9, 3: 8}
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-bde58578f7de> in <module>
      4 del(a)
      5 gc.collect()
----> 6 print(a)

NameError: name 'a' is not defined

Thus, you can use a combination of del() and gc.collect() to clear the variable from Python memory.

On a side note, though not very relevant, you can use the dir() method to get a list of the names of all the objects in the current scope.

a = 5
print(dir())
['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i7', '_ii', '_iii', 'a']
a = 5
print(dir())
del a
print(dir())
['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i10', '_i9', '_ii', '_iii', 'a']
['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i10', '_i9', '_ii', '_iii']

 

In order to understand more about garbage collection in general, do refer to https://docs.microsoft.com/en-us/dotnet/api/system.gc.collect?view=net-6.0

Also read: Python Variable Scope And Lifetime

Leave a Reply

Your email address will not be published. Required fields are marked *