pythongarbage-collectiondel

How does the `del` statement work in Python?


Suppose I have a variable x and then try del x. Does this free the allocated memory immediately, or will it still wait for the garbage collector to collect the object at some later point (like in Java)?


Solution

  • The del statement doesn't reclaim memory. It removes a reference, which decrements the reference count on the value. If the count is zero, the memory can be reclaimed. CPython will reclaim the memory immediately, there's no need to wait for the garbage collector to run.

    In fact, the garbage collector is only needed for reclaiming cyclic structures.

    As Waleed Khan says in his comment, Python memory management just works, you don't have to worry about it.