How to delete a variable in Python

In this tutorial, we will show you how to delete a variable in Python using different methods.

Updated March 29, 2023

Hello and welcome to this beginner’s tutorial on how to delete a variable in Python. Deleting a variable can be useful in order to free up memory and avoid naming conflicts. In this tutorial, we will show you how to delete a variable in Python using different methods.

Method 1: Using the del statement

The most common way to delete a variable in Python is to use the del statement. The del statement removes the reference to the object, which can then be garbage collected if there are no other references to it. To delete a variable using the del statement, simply specify the name of the variable that you want to delete, like this:

x = 5
del x

This will delete the variable x from the current namespace. You can also delete multiple variables at once by separating them with commas:

x = 5
y = "hello"
del x, y

This will delete the variables x and y from the current namespace.

Method 2: Using the globals() or locals() functions

Another way to delete a variable in Python is to use the globals() or locals() functions. These functions return a dictionary of the current global or local namespace, respectively. To delete a variable using globals() or locals(), you can use the del statement on the dictionary, like this:

x = 5
globals()['x'] = None

This will set the variable x to None in the global namespace, effectively deleting it.

Conclusion

In this tutorial, we have shown you two different ways to delete a variable in Python. Remember that deleting a variable can have unintended consequences, so make sure you are not deleting a variable that is still needed by your code. As always, test your code and make sure it works as expected.

Keep practicing and have fun with Python programming!

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!