Deepankar Bajpeyi
Deepankar Bajpeyi

Reputation: 5859

Will emptying a list release memory in Python?

Will this release memory in Python?

a = range(200)
a = []

Or do I have to specifically do del a?

SPORTS = ['cricket', 'football']

def handle(self, *args, **options):
    logger = logging.getLogger('load_articles')
    for sport in self.SPORTS:
        logger.info('setting sport')
        self.sport = sport
        self.load_articles_in_mem() #this populates the array articles
        obj, created = self.create_sport()
        self.create_articles_for(obj)
        self.articles = []
    logger.info("Articles loaded in memory %s" % len(self.articles))

So here articles get loaded into memory from some source, and as I increase the SPORTS list I would keep bloating the articles list. I could just empty the list inside the loop once everything I need was done.

Is there a more elegant way of doing this ?

Upvotes: 1

Views: 596

Answers (2)

Marek
Marek

Reputation: 1249

I have just checked for Python2.6 and created a = range(100000000) it consumed up to 700 MB of RAM. then a = [] it consumed additional 600 MB total of 1.3 GB of RAM. Then del a and nothing changed. The memory was released after I closed Python console.

For Python 3.4 range will not create any list - so it will not consume much memory. I have run a = range(1000000000000) and barely something changed with memory consumption.
But then I have run a = [x for x in range(10000000)] and it consumed around 200 MB then run a = [] and memory was released. Again created a = [x for x in range(10000000)] and it took 200 MB and then del a and memory was released.

Conclusion:
Py26 does not garbage collect unused list. Same for Py27. (just checked)
Py34 will garbage collect unused list and release memory.


PS.
I have runned in Python2.6 same test as for Python3.4. And the result was the same like previous. The memory was not released.

Upvotes: 5

Ihor Pomaranskyy
Ihor Pomaranskyy

Reputation: 5611

It should release memory, since there will be no references to the objects which where in list. But Python interpreter doesn't guarantee this, as far as I know.

Upvotes: 2

Related Questions