pythonmemorymemory-managementout-of-memorydealloc

Free memory in Python


How can I free part of list's memory in python? Can I do it in the following manner:

del list[0:j]  

or for single list node:

del list[j] 

Mark: My script analyzes huge lists and creates huge output that is why I need immediate memory deallocation.


Solution

  • You cannot really free memory manually in Python.

    Using del decreases the reference count of an object. Once that reference count reaches zero, the object will be freed when the garbage collector is run.

    So the best you can do is to run gc.collect() manually after del-ing a bunch of objects.


    In these cases the best advice is usually to try and change your algorithms. For example use a generator instead of a list as Thijs suggests in the comments.

    The other strategy is to throw hardware at the problem (buy more RAM). But this generally has financial and technical limits. :-)