How do I free up RAM in Python?

Last updated Jul 26, 2022

When your Python program deals with large files to process or store a large amount of data in memory, you are likely to run out of memory. A memory error occurs when a Python script fills all the available memory on a computer. In most cases, the memory error exception occurs when you're using a 32-bit installation that only has access to 4 GB of RAM. Since Python is a multipurpose programming language, 4 GB is insufficient. To prevent your Python program from running out of memory, you need to clear your variable data to free up your memory.

In this article, we will look at the two methods you should use to clear and free up your memory.  

There are two ways of clearing your RAM memory in Python:

  • Using the gc.collect() method

  • Using del Statement


Using a del Statement

Python also allows you to delete variables using the del statement. This statement allows us to delete large variables such as arrays or lists when the program no longer requires them. Whenever we run the delete statement, you will not be able to access or use it, and in that case, your Python program will raise a Name Error exception. To learn more about this method, see the example below. 


import numpy as np

myarray= np.array([4,5,6])

del myarray



How do I free up RAM in Python 1


Using the del statement and gc.collect() method

A del statement removes a variable from its namespace but not necessarily from its memory. As a result, after deleting the variable with the del statement, we can use the gc.collect() method to clear its memory.

Below is a Python example that uses the del statement and the gc.collect() method to clear the memory.


import numpy as np

import gc

myarray = np.array([4,5,6])

del myarray



How do I free up RAM in Python 2


Article Contributed By :


Subscribe For Daily Updates

Flutter Questions
Android Questions