How to delete a variable in Python?

How to delete a variable in Python

Python is a very versatile language. Much of its applicability, like other languages, comes from the fact that it is an Object Oriented Programming (OOP) Language. What is an Object Oriented Programming Language? Basically, an Object Oriented Programming Language is a programming language which uses Classes and Objects.

Normally, we don’t need to worry about the processes that happen inside the memory while we define a variable or object (or its deletion). This is because of the Garbage Collector, which is responsible to free unused memory so that it can be used elsewhere.

But first, let’s understand the processes that go on when a variable is declared, and what a variable actually is in python programming.

How Python Handles a Variable?

Inside python, every data structure (variables, list, tuples, dictionaries etc.) is an object. This isn’t the case with every language, but python is different in this scenario. Objects are instances of a class, which defines their properties and related methods.

So when we declare a variable in a python, we are actually declaring a reference to an instance of the related class. The value is actually stored in the object, we just give a reference to the object with which we can access the object.

The following code shows that every variable in python is an instance of the respective class.

Example:

var = 10
print(var)
print(type(var))

Output:

10

<class ‘int’>

Let’s discuss memory management in python in detail.

Memory Management in Python

In python, there are two types of memory:

  • Static Memory
  • Dynamic Memory

Python follows dynamic memory allocation for object instances. This is also known as run-time memory allocation as the memory is allocated to the object while the program is running. This is done using a heap data structure.

Static memory is used for method declarations and function call stack. This is implemented using the Stack data structure. This memory is allocated while the program is being interpreted and will not change during the running of the program, which is why it is called static memory.

When a variable is declared in python, mainly two processes take place:

  1. An object (or instance) of the respective class is created in the heap memory or runtime memory. It stores the data of the variable.
  2. A reference to this object is created in the static memory which holds the address of the instance in heap memory.

This process is important to understand if we want to understand the deletion of variables in Python.

Python does not require much manual intervention when it comes to memory management. 

All of the memory management is handled by Python Manager, which includes allocating memory to all variables and functions as well as maintaining the function call stack.

What happens when we delete a variable?

We have earlier discussed how a variable is declared and stored inside the memory. Now, let’s understand a few cases.

What if we initialise a variable equal to a pre-existing variable. In this case, the python memory does not create two separate memories in heap memory. Instead, it just creates another reference in the static memory and points it to the same instance in the heap memory as the pre-existing variable. Storing the address of a memory location is often described as pointing to the memory because it is easy to understand.

The Python Garbage Collector is a program which is responsible to free the unused memory in a program. It runs parallel to the program execution in the background and clears any memory that is being unused. This is very helpful in cases where the program is handling very large quantities of data or Big Data, which is one of the areas where python is the majorly used language.

So how does the garbage collector know which memory to delete? Any memory in the heap memory, which is not being referenced by any reference in the static memory is considered to be unused memory and is deleted. So, as long as a memory has at least one reference in the static memory, it would not be deleted.

When deleting a variable manually, we delete the reference in the static memory. This way, if there is no other reference to the memory in the static memory, the space is freed by the python garbage collector.

How to delete a variable in Python?

We have learnt how memory allocation and deallocation works in python, but a question arises, why do we need to delete variables manually or explicitly if there is the garbage collector in python for this very purpose? 

Well, in some cases, especially when handling big data, we may need to manually delete a variable according to the logic and working of our program.

Now, let us discuss some ways to delete a variable in python.

Using Del Keyword

The del keyword is an abbreviation for delete and is used to explicitly delete an object. Since we have already discussed that all data structures are objects in python, the del keyword can be used to delete variables, lists, tuples, dictionaries etc.

Syntax:

del variable_name

We can also delete multiple instances simultaneously using the del keyword, just like we can declare multiple objects in a single line.

Syntax:

del variable_1, variable_2, …

Example:

v1 = 5
v2 = 6
v3 = 7
v4 = 8
 
print(v1, v2, v3, v4)
 
# deleting single variable
del v1
 
# deleting multiple variables
del v2, v3, v4
 
print(v1, v2, v3, v4)

Output:

5 6 7 8

Traceback (most recent call last):

  File “main.py”, line 14, in <module>

    print(v1, v2, v3, v4)

NameError: name ‘v1’ is not defined

You must notice here that when we try to access the variable after deleting it, it gives NameError. This error is thrown when the given variable is not pointing to any valid heap memory location, or does not exist according to the python. This shows that the variable has been deleted.

Using dir() and globals()

This method is used to delete all the user-defined variables in a program. The dir() function returns a list of all inbuilt and user-defined variables and methods. The inbuilt objects and methods all can be identified as having the format : ‘__variable_name__’. The globals() works similar to the dir() method, besides the fact that it returns a dictionary, containing both the object name and their respective values.

This method works using the fact that if we delete an object or method name from dir() or globals(), we can delete the object itself. Let us see the implementation of this method.

Example:

v1 = 5
v2 = 6
 
d = dir()
gl = globals()
 
print(f'The dir() function returns the list : {d}')
print('')
print(f'The globals() function returns the dictionary : {gl}')
print('')

# code for deletion
for var in d:
    # check if it is a user-defined object
    if not var.startswith('__'):
        # if the variable is user-defined, delete the variable using del keyword
        del gl[var]
 
# try to print the variables
print(v1, v2)

Output:

The dir() function returns the list : [‘__annotations__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘v1’, ‘v2’]

The globals() function returns the dictionary : {‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <_frozen_importlib_external.SourceFileLoader object at 0x7feb1c4f73d0>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘__file__’: ‘main.py’, ‘__cached__’: None, ‘v1’: 5, ‘v2’: 6, ‘d’: [‘__annotations__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘v1’, ‘v2’], ‘gl’: {…}}

Traceback (most recent call last):

  File “main.py”, line 20, in <module>

    print(v1, v2)

NameError: name ‘v1’ is not defined

Conclusion

Deletion of an object in python is an important concept when dealing with large amounts of data. However, one should be very careful while deleting a variable, as it may lead to many difficult to spot errors.

Therefore, one should ensure carefully that the object is not to used again in the program. As practice, you may try to delete different data structures like lists, tuples etc. and observe the differences and similarities in the result.