Skip to Content

How to Clear Variables in Python – Explained!

How to Clear Variables in Python – Explained!

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)

 

Output

 

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)

 

How to Clear Variables in Python Output

How to Clear Variables in Python Output

 

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.

 

print(result)

 

Output clearing values in Python

Output clearing values in Python

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)

 

Output

 

The result is: 3.0
None None

 

 

What an EOFError in Python is
Previous
What an EOFError in Python is - Nailed it!
How to make a list of lists in Python
Next
How to Make a List of Lists in Python - Easy!