%resetto Clear All Variables in IPython - Requires User Confirmation
%reset -fto Clear All Variables in IPython - No User Confirmation
delto Clear a Specific Variable in IPython
magic('reset -sf')to Clear Variables Before Script Runs
This tutorial discusses methods to clear variables in IPython. Often, rerunning the same script in IPython behaves anomalously due to previous variables being still in the IPython memory. We will discuss how to clear the variables from IPython to avoid running into this situation.
%reset to Clear All Variables in IPython - Requires User Confirmation
The simplest way to clear all variables in IPython is by executing
%reset in IPython console. This command pops up a confirmation prompt before deleting the variables. The below example illustrates this:
Once deleted, variables cannot be recovered. Proceed (y/[n])? y
y deletes all the variables.
%reset -f to Clear All Variables in IPython - No User Confirmation
We can also use
%reset -f to clear all variables in IPython. The difference with
%reset is that
%reset -f requires no user confirmation. The below example illustrates this:
del to Clear a Specific Variable in IPython
If we want to clear any specific variable, we may use
del variable_name to achieve that. The below example illustrates this:
To delete more than 1 variable, we can do:
del variable1, variable2, variable3
magic('reset -sf') to Clear Variables Before Script Runs
The manual deletion effort adds extra overhead and requires to be done every time. A better approach will be to add a few code lines in the script we are running if we need to ensure that all the variables from memory are cleared before running the script. The below example illustrates this:
from IPython import get_ipython get_ipython().magic('reset -sf') #Your code
We discussed a few methods to clear variables in IPyhton. We can use
%reset to clear all variables with user confirmation,
%reset -f to clear all variables without user confirmation, and
del variable_name to delete a specific variable.
We have also discussed how to ensure that all variables are cleared from memory before running the script. Depending on the requirements, we may choose whichever method best fits.