How to Clear Variables in IPython

  1. Use %reset to Clear All Variables in IPython - Requires User Confirmation
  2. Use %reset -f to Clear All Variables in IPython - No User Confirmation
  3. Use del to Clear a Specific Variable in IPython
  4. Use magic('reset -sf') to Clear Variables Before Script Runs
  5. Conclusion

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.

Use %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:

%reset

Output:

Once deleted, variables cannot be recovered. Proceed (y/[n])? y

Typing in y deletes all the variables.

Use %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:

%reset -f

Use 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:

del variable1

To delete more than 1 variable, we can do:

del variable1, variable2, variable3

Use 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

Conclusion

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.