Deleting a Variable in Python

In this tutorial, we are going to learn how to delete a variable in Python. First of all, let’s get an idea about variables. Variables are the names given to the computer memory locations used to store values in a computer program. Since the name itself says that, the values of the variables can be changed.

A variable in Python is deleted using the del() function. Let’s gather some knowledge about del function.

Del() Function in Python

The del function deletes variables, lists, dictionaries and more. Similarly, it also deletes the single or multiple elements of a list or dictionary simultaneously.

Let’s see an example on del function.


a = "Hello, Welcome to Codespeedy"

In the above program, a variable named ‘a’ is created and assigned a string to it and simultaneously the variable is deleted. Finally, the output of the program is:-


Hello, Welcome to Codespeedy

Traceback (most recent call last):
File "", line 5, in <module>
NameError: name 'a' is not defined

At first, the program prints the string assigned to the variable ‘a’. In the next line, it prints an error stating that ” ‘a’ is not defined” because the variable is deleted in the third line of the program. Finally, as a result, we get an error.

Also, read:- Global Variables in Python

Leave a Reply

Your email address will not be published. Required fields are marked *