Python Forum

Full Version: Delete all variables except few
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I know how to use del var1, var2,... to delete multiple variables. However, this is not handy when I have to delete several variables. Is there an alternative to delete all variables except the ones that interests me? In MATLAB one can use clearvars -except var1 var2 ... to delete every variable except var 1, var 2. Is there something similar in Python?

I tried the below but this gives me an error after its execution NameError: name 'numpy' is not defined probably because I will need to import the modules again. Any suggestions to delete multiple variables without naming all of them one-by-one?

        for name in dir():
            if not name.startswith('_'):
                del globals()[name]
Why do you need to delete variables? Python garbage collector will take care for variables no longer referenced