How to Delete Variables & Objects from Memory

4.3/5 - (7 votes)

Problem Formulation and Solution Overview

This article will show you how to delete variables and objects from memory using the del or None keywords.

The Python language has several built-in reserved words having specific meanings called keywords. These keywords are reserved for Python and can not be used anywhere else. For example, declaring a variable, a list, an object, etc.

To display a list of Python keywords, run the following script.

import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

This article focuses on using the del or None keywords.


💬 Question: How would we write code to delete or clear objects from memory?

We can accomplish this task by one of the following options:

  • Method 1: Delete Variable using del or None from Memory
  • Method 2: Delete List or Dictionary using del or None from Memory
  • Method 3: Delete a Function using del or None from Memory
  • Method 4: Delete User Defined Objects with dir() and globals()
  • Method 5: Use the gc library

Method 1: Delete a Variable using del and None

This example uses the del and None keywords to delete and clear a variable and compares the differences.

puzzles_solved = 12975
print(puzzles_solved)

Above, we declared the variable puzzles_solved, set the value to 12975 and output the same to the terminal.

12975

However, if the value of puzzles_solved was set to None, this does not delete the variable from memory. Instead, it clears the value.

puzzles_solved = None
print(puzzles_solved)

This is confirmed by sending the contents of puzzles_solved to the terminal.

None

The del keyword must be used to remove a variable entirely from memory.

puzzles_solved = 12975
del puzzles_solved
print(puzzles_solved)

Sending the output to the terminal displays a NameError message. The variable no longer exists!

NameError: name 'puzzles_solved' is not defined

Method 2: Delete a List or a Dictionary

This example uses the del and None keywords to delete a List and a Dictionary and compares the differences.

user_list = [212, 215, 387, 598, 610]
user_dict = {212: 'Tom', 215: 'Amy', 387: 'Rob', 598: 'Carl', 610: 'Raj'}

print(user_list)
print(user_dict)

Above, creates a List containing fictitious Finxter User IDs user_list. This saves to user_list. Next, a Dictionary is created containing fictitious Finxter data (id and name). This saves to user_dict.

💡Note: This example shows the deletion of a List and a Dictionary. However, any object can be removed using the del keyword.

Both are output to the terminal.

[212, 215, 387, 598, 610]
{212: 'Tom', 215: 'Amy', 387: 'Rob', 598: 'Carl', 610: 'Raj'}

However, if these variables were set to None, this would not delete the variables from memory. Instead, it clears the value(s).

user_list = None
user_dict = None

print(user_list)
print(user_dict)

This is confirmed by the following output to the terminal.

None
None

The del keyword must be used to remove a variable entirely from memory.

del user_list
del user_dict

print(user_list)
print(user_dict)

Sending the output to the terminal displays a NameError message. The variable no longer exists!

NameError: name 'user_list' is not defined

💡Note: The second print() statement does not execute as execution terminates once the script receives an error.

Python Dictionary – The Ultimate Guide

Method 3: Delete Function from Memory

This example uses the del keyword to remove an existing function from memory.

def  add_me(a, b):
    return a+b
print(add_me(2,3))

del add_me
print(add_me(2,3))

Above defines the function add_me that adds two (2) numbers and returns the result. The result is output to the terminal.

5

This function is then deleted using the del keyword. Sending the output to the terminal displays a NameError message. The function no longer exists!

NameError: name 'add_me' is not defined

Method 4: Delete User Defined Objects with dir() and globals()

This example deletes User Defined Objects with the dir() and globals() functions.

def add_me(a, b):
    return a+b

def subtract_me(a, b):
    return a-b

print(dir())

Above declares two (2) functions, add_me() and subtract_me(). Both return a calculated result.

After running this code, these functions should exist in memory. The results of dir() are sent to the terminal to confirm this.

'__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add_me', 'subtract_me']

If used without argument, Python’s built-in dir() function returns the function and variable names defined in the local scope—the namespace of your current module.

If used with an object argumentdir(object) returns a list of attribute and method names defined in the object’s scope. Thus, dir() returns all names in a given scope.

🌍 Source: The Finxter Academy

for el in dir():
    if el[0:2] != "__":
        del globals()[el]

The following for loop iterates through each element in the dir() results. If the first two (2) characters start with '__' the element(s) are ignored.

If that is not the case, this code deletes the element (el) using the globals() function by appending the element (del globals()[el]) to remove.

The results of dir() are sent to the terminal to confirm the deletion.

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

💡Note: The two (2) function created earlier are removed. However, the variable el now resides in memory.

Python dir() — A Simple Guide with Video

Method 5: Use gc library

This example imports the gc library. This library, also referred to as the generational garbage collector, keeps track of all objects in memory.

If the gc library is not installed on the computer, click here for instructions.

import gc

user_list = [212, 215, 387, 598, 610]

del user_list
gc.collect()
print(dir())

del gc
print(dir())

Above, imports the gc library.

Then a fictitious list of Finxter Users is declared and saved to user_list. The following line deletes this.

Then, the gc.collect() function is called, and the results are output to the terminal.

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

Note, the gc class displays.

The following line deletes this class. The output is sent to the terminal.

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

🧩A Finxter Challenge!
How would you delete el used Method 4?


Summary

These five (5) methods of deleting variables and objects from memory should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Programming Humor – Python

“I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I’m leaving you.”xkcd