Python Forum
Delete all variables except few
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Delete all variables except few
#1
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]
Reply
#2
Why do you need to delete variables? Python garbage collector will take care for variables no longer referenced
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020