How to remove the variables in python to clear ram memory in python?
R :
a = 2
rm(a)
Python:
a = 2
How to clear the single variables or a group of variables?
python memory cleanup is managed by the garbage collector. on CPython it is based on reference counting. you can call the garbage collector explicitly like this:
import gc
gc.collect()
this can be done after calling a function that uses large variables in terms of ram. Note that you do not have to call this function explicitly as the garbage collector will be called eventually to free up ram automatically.
if you still want to explicitly remove a variable you can use the del statement (as written before) like this:
x = [1, 2, 3]
i = 42
s = 'abc'
del s # delete string
del x[1] # delete single item in a list
del x, i # delete multiple variables in one statement
to better understand what del
does and its limitations lets take a look at how python stores variables on ram.
x = [1, 2, 3]
the above code creates a reference between the name x
to the list [1, 2, 3]
which is stored on the heap. x
is just a pointer to that list.
x = [1, 2, 3]
y = x
x is y # True
in this example we have the reference x
and the list on the heap [1, 2, 3]
, but what is this new y
variable? its just another pointer, meaning now we have two pointers to the same [1, 2, 3]
list.
returning to the del
statement, if we delete one variable it wont affect the list or the other variable
x = [1, 2, 3]
y = x
del x
print(y) # prints [1, 2, 3]
so here we will not free up the list, only decrease the reference counting to the list but we still have y
pointing to it.
to overcome this we can use the weakref module to point y
to the list and when x
is deleted the list is also deleted.
gc.collect()
after heavy memory functionsdel x, y
to delete all pointers to a specific object to free it upweakref
module to avoid holding objects on the ram after all other references to them are deletedUse del
>>> a=2
>>> del a
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With