Garbage collection is a term used in object orientated programming. When you are programming, you create all kinds of objects (including variables like int,string,boolean,hashmap). These all need to be stored into the computers memory, but most programs never delete them.

When you make a program, you may create thousands of objects. All of these objects hold space in your computers memory. You don’t want to manage all that memory manually, meet memory mangement.

Related course: Python Programming Courses & Exercises

Introduction

In older programming languages, developers had to remove them from the memory themself. They included functions like malloc to register a memory block. Python being a high-level programming language does this for you.

In Python, you don’t need to worry about registring memory blocks or deleting things from the memory. Python does that for you, and this is named garbage collection.

Garbage collection (GC) is a type of automatic memory management, which the garbage collector reclaims memory occupied by objects that are no longer in use by the program (e.g. garbage).

Older programming languages often had problems like memory running full, as developers sometimes forgot to clear memory or it had memory leaks. Sometimes they freed the memory to soon, leading the programs to crash.

Garbage Collection in Python

Python supports garbage collection, which means it takes care of the memory for you. But in some programming languages you have to clean objects yourself (C,C++).

You can delete objects manually if you want to, this cleans up your computer memory.
To delete an object you can use the del keyword.

del my_object

If the object no longer exists, you get the following error:

>>> del my_object
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'my_object' is not defined
>>>

Everything is an object in Python: we define a simple variable x and use that.
During runtime we delete the object and try to output it.

x = 3
print(x)
del x
print(x)
This will output:
3
Traceback (most recent call last):
File "t.py", line 5, in <module>
print(x)
NameError: name 'x' is not defined

In the first 2 lines of the program object x is known. After deletion of the
object x cannot be printed anymore.

Garbage collection is completely automated, you do not have to worry about it.

The del() destructor is called just before an object is destroyed.

If you are a Python beginner, then I highly recommend this book.

Download exercises