The Python Oracle

How to clear variables in ipython?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon

--

Chapters
00:00 How To Clear Variables In Ipython?
00:22 Accepted Answer Score 265
00:31 Answer 2 Score 72
01:13 Answer 3 Score 17
01:34 Answer 4 Score 67
01:41 Thank you

--

Full question
https://stackoverflow.com/questions/2293...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #memory #ipython

#avk47



ACCEPTED ANSWER

Score 265


%reset seems to clear defined variables.




ANSWER 2

Score 72


EDITED after @ErdemKAYA comment.

To erase a variable, use the magic command:

%reset_selective <regular_expression>

The variables that are erased from the namespace are the one matching the given <regular_expression>.

Therefore

%reset_selective -f a 

will erase all the variables containing an a.

Instead, to erase only a and not aa:

In: a, aa = 1, 2
In: %reset_selective -f "^a$"
In: a  # raise NameError
In: aa  # returns 2

see as well %reset_selective? for more examples and https://regexone.com/ for a regex tutorial.

To erase all the variables in the namespace see:

%reset?



ANSWER 3

Score 67


In iPython you can remove a single variable like this:

del x



ANSWER 4

Score 17


Adding the following lines to a new script will clear all variables each time you rerun the script:

from IPython import get_ipython
get_ipython().magic('reset -sf') 

To make life easy, you can add them to your default template.

In Spyder: Tools>Preferences>Editor>Edit template