how to release used memory immediately in python list?

def release_list(a):
   del a[:]
   del a

Do not ever do this. Python automatically frees all objects that are not referenced any more, so a simple del a ensures that the list’s memory will be released if the list isn’t referenced anywhere else. If that’s the case, then the individual list items will also be released (and any objects referenced only from them, and so on and so on), unless some of the individual items were also still referenced.

That means the only time when del a[:]; del a will release more than del a on its own is when the list is referenced somewhere else. This is precisely when you shouldn’t be emptying out the list: someone else is still using it!!!

Basically, you shouldn’t be thinking about managing pieces of memory. Instead, think about managing references to objects. In 99% of all Python code, Python cleans up everything you don’t need pretty soon after the last time you needed it, and there’s no problem. Every time a function finishes all the local variables in that function “die”, and if they were pointing to objects that are not referenced anywhere else they’ll be deleted, and that will cascade to everything contained within those objects.

The only time you need to think about it is when you have a large object (say a huge list), you do something with it, and then you begin a long-running (or memory intensive) sub-computation, where the large object isn’t needed for the sub-computation. Because you have a reference to it, the large object won’t be released until the sub-computation finishes and then you return. In that sort of case (and only that sort of case), you can explicitly del your reference to the large object before you begin the sub-computation, so that the large object can be freed earlier (if no-one else is using it; if a caller passed the object in to you and the caller does still need it after you return, you’ll be very glad that it doesn’t get released).

Leave a Comment