Member-only story
Garbage Collection in Python
The process of reclaiming memory

If you’ve been programming for a while, you’ve probably heard about garbage collection. Let’s delve deeper into what it is and how it works.
What and Why
In the real world, we clear out things — e.g., old notes, boxes that we no longer need — and discard them in a garbage/recycling can. Space is limited, and we want to make space for other essential items we want to store.
Similarly, in computers, space — aka memory — is an important and finite resource. Thus, a garbage collector collects data objects that are no longer needed and discards them.
Depending on the language, garbage collection can be an automatic or a manual process. In most high-level languages, such as Python and Java, it’s automated. Thus, these languages are called garbage-collected languages. Other languages, such as C, don’t support automatic garbage collection, and the programmer is responsible for memory management.
Now, let’s see how garbage collection works.
How
There are some techniques, but most garbage-collected languages, including Python, use reference counting. In reference counting, we track the number of references to an object and discard an object when the count is 0
.