Today, we will learn how to clear variables in Python. Let’s say you created a variable initially, and you no longer require it.
So, keeping it is useless and is wasting memory as well. Therefore, you can do two things. If the variable is not required later, then you can delete it completely. Otherwise, you can clear its value.
Deleting a variable
If you delete a variable, you cannot use it later as it will be removed from the memory. You can delete a variable using the del keyword. Let’s take an example.
val1 = 15 val2 = 5 result = val1/val2 del val1 del val2 print("The result is:", result)
The result is: 3.0
Since val1 and val2 are not required, we delete them. If we try to refer to it later, we will get an error. Let’s see.
val1 = 15 val2 = 5 result = val1/val2 del val1 del val2 print("The result is:", result) print(val2)
Deleting All Variables
If you want to delete all the created variables, you can also do that. The dir() method returns the list of names in the current local scope.
If the variable does not start with __, then it is a user-defined variable. Therefore, you can delete it using the globals() method. It returns a dictionary that contains the global variables of the current scope.
val1 = 15 val2 = 5 result = val1/val2 objects = dir() for obj in objects: if not obj.startswith("__"): del globals()[obj]
If we try to access a user-defined object now, we will get an error.
Note that if you start your variable with __, then it won’t get deleted because you are excluding such types of names. You will have to remove it manually.
Clear the value of the variable
Clearing the value of the variable is quite simple. We only have to assign None to it. Note that the variable still exists in the memory, and therefore you can refer to it. It just does not have any value assigned to it.
Let’s have a look at an example.
val1 = 15 val2 = 5 result = val1/val2 val1 = val2 = None #clearing values print("The result is:", result) print(val1, val2)
The result is: 3.0 None None
Hey guys! It’s me, Marcel, aka Maschi. I earn a full-time income online and on MaschiTuts I gladly share with you guys how I stay on top of the game! I run several highly profitable blogs & websites and love to speak about these project whenever I get a chance to do so. I do this full-time and wholeheartedly. In fact, the moment I stopped working an 8-to-5 job and finally got into online business as a digital entrepreneur, is problably one of the best decisions I ever took in my life. And I would like to make sure that YOU can get on this path as well! Don’t let anyone tell you that this can’t be done. Sky’s the limit, really…as long as you BELIEVE in it! And it all starts right here..at Maschituts!