Delete multiple variables in Python 3 independently if they exist or not


With del a, b, c I can delete 3 variables at once if all variables a, b, c exist. However if a variable does not exists I get an error.

If I would like to delete variables a, b, c I could beforehand manually check its existence:

a = 1
b = 1
if 'a' in locals(): del a
if 'b' in locals(): del b
if 'c' in locals(): del c

This is quite cumbersome as I often want to delete multiple variables. Is there a more comfortable way similar to del a, b, c?

Why do I want to delete variables?

The Variable Explorer (e.g. in Spyder or other IDE) lists all my variables. For better overview I want to see only the important variables. Temporary variables that are used only for auxiliary purpose are not needed later and therefore do not have to appear in the Variable Explorer. Also memory is freed if auxiliary variables are deleted.

Asked By: granular bastard



One way that you could technically accomplish what you want would be this:

b1 = 1
b2 = 2
# b3 = 3 # commented to make it not exist
for name in {"b1","b2","b3"}:
    exec(f"del {name}")
  except NameError:

This will delete every variable name put in the list, which must be strings to avoid NameError right away.

However, I heavily recommend against this. The debugger is, as its name implies, only intended be used to debug. For actual program output you should use print statements, or some GUI if you want to be more friendly.

Example of some program output using f-strings:

print(f"Average {avg}, max {max_val}, mode {mode}, winner {}")
print(f"Loser: {}")

Here’s a modification of the other answer that allows use in a function, assuming you are only deleting locals.

def del_all(locals_v, *args):
    for v in args:
        locals_v.pop(v, None)

x1, x3 = 1, 3

You could do globals() inside the function instead, as shown in the other answer, but then of course it only work if you were always working in the global scope, and wouldn’t work when you are inside of any function.

Answered By: Luke B

A initialized variable, a = 1, is stored as a key-value pair, {"a": 1}, in a dictionary which is accessible via locals, globals built-ins.
Use dict.pop with a default value to remove the variable.

It is better to work with care when operating on locals(), globals() dictionaries, see comment of Mark Tolonen for details and reference to the doc.

#variables initialization
x1, x3 = 1, 3

# variables identifiers
to_del = "x1", "x2", "x3"

# delete the variables
for var_id in to_del:
    globals().pop(var_id, None)

# check

EDIT: from the comment, in the form of a function

def g_cleaner(to_del:list[str]) -> None:
    """global cleaner"""
    for var_id in to_del:
        globals().pop(var_id, None)

#NameError: name 'x1' is not defined

alternative version

def g_cleaner(*to_del:list[str]) -> None:
    """global cleaner"""
    for var_id in to_del:
        globals().pop(var_id, None)

# for list-like arguments (unpacking)
#NameError: name 'x1' is not defined

# for specific values
g_cleaner("x1", "x2") # quotes are needed!
#NameError: name 'x1' is not defined
Answered By: cards
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.