Internally, Python use a mechanism called reference counting to keep track if a data is still accessible or not. Each time a new "variable" references a data, the reference counter of the data is increased. Each time a "variable" cease to reference a data, the reference counter of the data is decremented. When the reference counter reach 0, the data is deleted (its "deallocation function" is invoked): http://docs.python.org/2/c-api/refcounting.html
For example, this create a "big" list, which is deleted almost as soon as it is created since there is no variable to "increase" its reference counter:
range(1, 10000)
This create a new list, allow you to reference it through my_list
and set the reference counter of the list to "1"
my_list = range(1, 10000)
Writing the following statement, will now decrease the reference counter of the list. Assuming you have no other references to it, that counter reach 0 and so the list is deleted.
my_list = None
A last example:
my_list = range(1, 10000)
del my_list[:]
This one create a list of 10000 items. With a reference counter of "1". The second statement delete the 10000 items of the list -- but you still have one reference to an empty list. You see the difference?
BTW, reference counting is a great mechanism for automatic deallocation and it has the benefit of being determinist (as the opposite of the Java garbage collector). But, there is one case where reference counting does not work: if you have circular dependencies. Object A references object B which references object A. In that case, none of the A or B reference counter could reach 0 as long as the "circle" is not broken. But this is beyond your question, I assume. Anyway, for those programs containing non-mastered circular dependencies, Python has an optional garbage collector to free such cycles. By default that garbage collector is enabled. It's easy to check:
>>> import gc
>>> gc.isenabled()
True
As a final note, even that garbage collector is limited since it does not deallocate cycles containing objects with finalizer (__del__
). See the following link for rational about that http://arctrix.com/nas/python/gc/