Is it possible to delete variable in Python? [SOLVED]

A Python variable is a symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name. A variable in Python can store any data type. In this short article about 'Python delete variable", we will learn how we can delete a variable that we already had declared in Python. We will use various examples to learn how to delete variables in Python.

 

What is a variable in Python?

A Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing. Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Unlike other many programming languages, we don't need to specify the data type of the variable while declaring it. The data type of variable in Python is defined by the type of data we store in it.

Advertisement

For example, see the following example:

# decaring and initializing varible in Python
var1 = 23
var2 = 2.333
var3 = 'this is me'
var4 = [1,2,3,4]

# printing the data types
print(type(var1))
print(type(var2))
print(type(var3))
print(type(var4))

Output:

python-delete-variable

As you can see each of the variables has a different data type because we have stored different data.

 

How is memory managed in Python?

In Python, there are two types of memory locations.

  • Static memory location
  • Dynamic memory location

Since Python uses dynamic memory allocation for variables, memory allocation takes place while the program is running. A Heap data structure is used to implement the dynamic memory allocation. In addition to the heap data structure, static memory is stored in the stack data structure. Keep in mind that Python distinguishes between static and dynamic memory.

 

Why delete a variable in Python?

One of the most important considerations while working with Python or any other programming language is memory management. You must be asking yourself why memory management is so crucial. When you're writing any program, you never even notice how it influences your code. You'll see how this memory management affects the overall effectiveness and processing speed of your software while working with massive data.

Advertisement

So, how does Python delete variables work? Well, as discussed earlier, Python has a Python memory manager, which is responsible for the allocation or de-allocation of the memory heap. The memory Heap in Python holds the objects and other data structures used in the program. So, when a variable (a reference to an object) is no longer in use, the Python memory manager frees up the space, i.e. it removes the unnecessary object. This process of removing objects, which are no longer in use, is known as Garbage Collection.

 

Python delete variable using different methods

So far, we discussed what is a variable in Python, how to declare it, and how the memory location works in Python. Now, let us jump into the Python delete variables using different methods. Here we will be discussing two different methods to delete a variable in Python.

  • Using del keyword
  • Using dir() method

Let us now delete variables in Python by using the above methods.

 

Method-1 Using del keyword

Python keywords are special reserved words that have specific meanings and purposes and can't be used for anything but those specific purposes. These keywords are always available—you'll never have to import them into your code. One of the keywords in Python is del which is used to delete variables.

For example, let us create a simple program where we will delete a variable.

# variable
var = 25

# printing variable
print(var)

# Python delete variable
del var

# printig
print(var)

Output:

Advertisement

Python-delete-variable-del-keyword

As you can see, first we were able to print the variable, then we deleted the variable using the del keyword.

More importantly, we can even delete multiple variables using the del keyword as well. For example, now we will initialize different variables and will delete them using the del keyword.

# decaring and initializing varible in Python
var1 = 23
var2 = 2.333
var3 = 'this is me'
var4 = [1,2,3,4]

# Python delete variable
del var1, var2, var3, var4

Now, if u will try to access any of these variables, you will get an error because the del keyword has deleted those variables.

 

Method-2 Using dir() method

The second method to delete Python variables is not direct as del does. The dir() method returns the all properties and methods of a specified object. Even when no object is referenced, it returns a list of all the variables and built-in methods used in your program. For example, let us create some variables and apply the dir() method.

# decaring and initializing varible in Python
var1 = 23
var2 = 2.333
var3 = 'this is me'
var4 = [1,2,3,4]


#inititalizing d with dir()
d = dir()

#printing the directory
print(d)

Output:

['_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i2', '_i3', '_i4', '_i5', '_ih', '_ii', '_iii', '_oh', 'exit', 'get_ipython', 'quit', 'var1', 'var2', 'var3', 'var4']

As you can see, the dir() method returned all the variables including built-in variables and user-defined variables. The difference between them is that user-defined variables are with the same name as they were declared while built-in variables start with an underscore(_).

Advertisement

Another useful method that returns all variables is global(). This method returns all the variables along with their values as well.

What we can do is we can list all variables and then delete the variables that do not start with an underscore because all the built-in variables start with underscores. Let's solve one example to understand it.

# decaring and initializing varible in Python
var1 = 23
var2 = 2.333
var3 = 'this is me'
var4 = [1,2,3,4]


#initializing d with dir()
d = dir()

# checking user defined variables
for obj in d:
    
    #checking for built-in variables
    if not obj.startswith('__'):
        
        # python delete variable
        del globals()[obj]

# printing python delete variable
print(var1)

Output:

error-in-variable

As you can see, we get an error because we have deleted the variables.

 

Summary

A Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing. In this short article, we learned how we can delete variables using two different methods. Moreover, we solve various examples to understand the concept better.

 

Further Reading

Clear variable in python - Stack Overflow

Advertisement

 

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X