Skip to main content
Practice

How to Manage Memory with Garbage Collection

Garbage Collection is a memory management system that automatically manages and removes objects that are no longer in use (unreferenced memory).

Memory is the area of a computer where data is temporarily stored during program execution. Once the program finishes or data is no longer needed, memory can be released.


Garbage collection plays an important role in preventing memory leaks and improving the efficiency of a program's memory usage.


When a Class Stores Variables

When a class stores a variable, any object it references will stay in memory as long as the reference exists.

The object remains in memory until it is no longer referenced, at which point it becomes eligible for garbage collection.

Example of a Class Storing Variables
class MyClass:
def __init__(self, data):
self.data = data

# Creating and referencing the object
obj = MyClass([1, 2, 3])

In this example, the obj object references an instance of MyClass, storing the list [1, 2, 3] in the data variable. As long as obj exists, garbage collection will not reclaim this object.


When a Class Does Not Store Variables

If a class instance is not referenced by any variable, Python’s garbage collector will automatically reclaim its memory.


Example of a Class Not Storing Variables
class MyClass:
pass

# Creating and referencing the object
obj = MyClass()

# Removing the reference
del obj # Target for garbage collection

In this example, obj references an instance of MyClass.

When del obj is called to remove the reference, garbage collection can reclaim the MyClass instance.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.