- How to delete or clear variable from memory in Python?
- The del keyword
- The gc.collect() method in Python
- Как удалить переменную в Python
- 2 Different Ways to Clear Memory in Python
- What is del method?
- Syntax
- Parameter
- Ways to Clear Memory in Python
- 1. How to clear a variable?
- 2. How to clear a list?
- 3. How to clear an array?
- What are the problems we will face while clear the memory in python?
- What is gc.collect() method?
- Clear the memory in python using gc.collect() method
- 1. How to clear a variable using gc.collect()?
- 2. How to clear a list using gc.collect()?
- How to clear an array using gc.collect()?
- How to identify and fix memory leaks?
- Finding the memory leaks in python
- Fixing memory leaks in python
- FAQs Related to clear memory in python
- Conclusion
How to delete or clear variable from memory in Python?
Computer memory is very important not just for storing data, code and instructions but also for the system’s performance. Variables are the simplest and most basic storage units. You must be knowing that Python variables are dynamically typed, i.e, they are declared as and when they are assigned/used.
Sometimes, even though you assigned a variable with some value in the program, you may realize later that that variable is not necessary. In such a scenario, you will want to delete that variable both from your program as well as your memory.
In this tutorial, you will understand how to delete a variable from the memory space in Python.
The del keyword
It is used to simply delete any Python object. (variables,arrays,lists,dictionaries etc).
Syntax: del(element to be deleted)
You can look into the below-coded example to understand this better.
Example 1: Deleting a variable
--------------------------------------------------------------------------- NameError Traceback (most recent call last) in 2 print(a) 3 del(a) ----> 4 print(a) NameError: name 'a' is not defined
Note: The del method can be used not just with variables but with all Python objects like arrays, lists, dictionaries etc.
Example 2: Deleting a list
--------------------------------------------------------------------------- NameError Traceback (most recent call last) in 2 print(a) 3 del(a) ----> 4 print(a) NameError: name 'a' is not defined
In this case, the program returns a NameError exception. This is because the variable you are trying to access no longer exists in the variable namespace.
However, the above del method only removes the variable from the namespace. It does not remove the variable from the memory space.
Well, so how do we permanently remove the variable and clear its memory?
The gc.collect() method in Python
The del method does not clear the variable from the memory. Hence, to clear the variable from memory you can resort to the gc.collect() method.
The gc.collect() method forces an immediate garbage collection of all generations. You can invoke the garbage collector as demonstrated below.
Example 1: Deleting a variable
import gc a=10 print(a) del(a) gc.collect() print(a)
NameError Traceback (most recent call last) in 4 del(a) 5 gc.collect() ----> 6 print(a) NameError: name 'a' is not defined
In this case, you are deleting a from the memory space itself.
Just like the del method, you can invoke the gc.collect() for clearing the memory of not just variables but for all Python objects.
Example 2: Deleting a dictionary
import gc a= print(a) del(a) gc.collect() print(a)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) in 4 del(a) 5 gc.collect() ----> 6 print(a) NameError: name 'a' is not defined
Thus, you can use a combination of del() and gc.collect() to clear the variable from Python memory.
On a side note, though not very relevant, you can use the dir() method to get a list of the names of all the objects in the current scope.
['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i7', '_ii', '_iii', 'a']
a = 5 print(dir()) del a print(dir())
['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i10', '_i9', '_ii', '_iii', 'a'] ['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i10', '_i9', '_ii', '_iii']
Как удалить переменную в Python
Любая переменная занимает место в памяти. Не то чтобы это очень страшно на современных мощных компьютерах, однако иногда всё-таки необходимость удалить ссылку на переменную возникает.
В Python не обязательно заранее объявлять переменные. В любом месте программы вы может, например, написать так:
И это будет означать, что отныне в программе есть переменная х , которой присвоено значение 100 (подробнее о присваивании здесь). И теперь вы можете использовать эту переменную в своей программе: присваивать ей новые значения, вставлять в выражения и т.п.
Если же по какой-то причине вы больше не хотите видеть переменную х в своей программе, то вы можете удалить её с помощью инструкции del вот так:
После этого вы уже не сможете использовать переменную х в вашей программе, поскольку ссылка на неё будет удалена. Ссылка на переменную х отныне будет генерировать исключение NameError , и при попытке обращения к этой переменной будет выдано сообщение об ошибке:
Если же вам снова потребуется переменная х , то надо будет просто заново объявить её.
Инструкция del может быть использована и для других целей. Но об этом в другой раз. А сейчас для ясности можете посмотреть видео по теме данной статьи:
2 Different Ways to Clear Memory in Python
We will learn how to clear or delete a memory in python. There is a way to delete a memory for the unused variables, list, or array to save the memory. We will learn how to clear memory for a variable, list, and array using two different methods. The two different methods are del and gc.collect().
del and gc.collect() are the two different methods to delete the memory in python. The clear memory method is helpful to prevent the overflow of memory. We can delete that memory whenever we have an unused variable, list, or array using these two methods. It will save the memory. As efficient programmers, we need to know how to save memory. So these two methods are beneficial for the programmers.
What is del method?
del method is useful to delete unused variables, lists, and arrays. This method is useful to save memory allocation.
Syntax
Parameter
element: It may be a variable, list, or array that we want to delete.
Ways to Clear Memory in Python
1. How to clear a variable?
Here we have created a variable a. After that, we have deleted that variable using the del statement. This is means clearing the memory in python. Now we will try to print the variable. Let us see what the output is while we print the variable.
Traceback (most recent call last): File "C:\Users\AppData\Local\Programs\Python\Python39\io.py", line 17, in print(a) NameError: name 'a' is not defined
2. How to clear a list?
lst=[10,80,60,45] del lst print(lst)
In the above program, we are going to clear a list using a del command. After deleting a list, we are trying to print the list whether the list is successfully created or not. While the program hits the print(list) statement, if it returns a Name error, the list is deleted successfully.
Traceback (most recent call last): File "C:\Users\AppData\Local\Programs\Python\Python39\io.py", line 17, in print(lst) NameError: name 'lst' is not defined
3. How to clear an array?
import numpy as np array=np.array([1,2,3,4]) del(array) print(array)
Let us take an array and delete it using a del command. After deleting that, let us see the output for print(array).
Traceback (most recent call last): File "C:\Users\AppData\Local\Programs\Python\Python39\io.py", line 22, in print(array) NameError: name 'array' is not defined
What are the problems we will face while clear the memory in python?
We have seen a lot of examples to clear the memory by using the del method. After using this type of statement, the objects are no longer accessible for the given code. But, the objects are still there in the memory.
To solve this issue, python introduced gc.collect() method to clear the memory. Python introduced gc module in the version of python 1.5.
What is gc.collect() method?
gc.collect is a method that is useful to prevent the overflow of memory. It will delete the elements.
Clear the memory in python using gc.collect() method
1. How to clear a variable using gc.collect()?
import gc a=10 del a gc.collect() print(a)
Import gc. Create a variable a is equal to 10. Delete a. Now we will check using a print statement.
Traceback (most recent call last): File "C:\Users\AppData\Local\Programs\Python\Python39\io.py", line 28, in print(a) NameError: name 'a' is not defined
2. How to clear a list using gc.collect()?
import gc lst=[1,6,3,68] del lst gc.collect() print(lst)
Import gc. I am creating a list in a variable list. Now the list is deleted successfully.
Traceback (most recent call last): File "C:\Users\AppData\Local\Programs\Python\Python39\io.py", line 28, in print(lst) NameError: name 'lst' is not defined
How to clear an array using gc.collect()?
import numpy as np import gc array=np.array([1,6,3,68]) del array gc.collect() print(array)
Import gc. Create an array. Make use of the del command to delete the memory created for the array.
Traceback (most recent call last): File "C:\Users\AppData\Local\Programs\Python\Python39\io.py", line 29, in print(array) NameError: name 'array' is not defined
How to identify and fix memory leaks?
When the programmer forgets to delete an unused memory, then the memory will get overflow, and it causes memory leaks. Memory link will cause because of lingering large objects which are not released and reference cycles within the code.
Finding the memory leaks in python
GC module is helpful to debug the memory leaks in python. It provides the garbage collector, has a list of all objects. This module will give an idea of where the program’s memory is being used. Then the objects are filtered. GC module will identify the unused objects so that the user can delete the unused memory. This will prevent memory leaks in python.
The GC module will tell the information about how many objects are created. Still, it does not give the information about how the objects are being allocated so that it would have no use in identifying the code causing memory leaks.
Fixing memory leaks in python
Python introduced a built-in function named Tracemalloc module. This module is presented in the version of python 3.4. It is helpful for solving memory leaks in python. Tracemallc module provides block-level traces of memory allocation. This will tell where the memory was allocated.
FAQs Related to clear memory in python
del and gc.collect() are the available methods to clear the memory in python.
Conclusion
So far, we have wholly learned about how to clear the memory in python. We have learned a lot of things in this article. These are the beneficial and necessary things to learn as a python programmer.
We hope this article is easy to understand. In case of any queries, do let us know in the comment section.