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.
Example:-
a = "Hello, Welcome to Codespeedy" print(a) print() del(a) print(a)
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:-
Output:-
Hello, Welcome to Codespeedy Traceback (most recent call last): File "filename.py", line 5, in <module> print(a) 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
please note that del is a keyword not a function and ” del var ” is valid code (no brackets needed)