Skip to main content

How to Free Up RAM in Python with gc.collect()

As an experienced Python programmer knows, memory errors can be a real pain. They usually occur when your script is trying to deal with large files or a lot of data. To prevent this, you need to clear your variable data to free up your memory. Python is a multipurpose programming language, so it’s important to have enough RAM available.

To avoid your Python program from crashing due to memory limit, you must clear your variable data to free up space in your RAM. In this article, we will look at two methods for clearing and freeing up your memory in Python.  

Using del Statement 

A way to clear the RAM is by using the del statement on each variable individually after you’re done using them. This will remove the variable from your namespace so that it doesn’t take up any more memory than necessary. This statement is useful when you need to delete large variables like huge lists or dictionaries.

import numpy as np
big_array = np.arange(1,700)
print(big_array)
del big_array
print(big_array)

However, del doesn’t call the garbage collector automatically so you’ll need to do that yourself if you want to clear up unused memory. 

Using the gc.collect() Method

The gc module provides the function gc.collect(). This method calls the garbage collector to collect all unreferenced objects and frees up memory.

If you have a lot of unreferenced objects, calling gc.collect() will take some time. It’s best to call it when your program is not doing anything else so that it doesn’t slow down your program unnecessarily. 

import numpy as np
import gc
big_array = np.arange(1,700)
print(big_array)
del big_array
gc.collect()
print(big_array)

In general, it’s best not to create too many unnecessary variables because they take up memory and can slow down your program unnecessarily. You should only create them when you need them and delete them when you’re done using them so that they don’t take up any more memory than necessary. 

By continuing to use the site, you agree to the use of cookies.