Every object your program creates takes up memory, and garbage collection is how that memory gets handed back once nothing needs the object any more. How it works explains why some apps slowly eat memory and others pause for no obvious reason.
What counts as garbage
When a program creates an object, such as a list or an instance of a class, the runtime sets aside space for it on the heap, the area of memory used for data that outlives a single function call. Your code then holds references to that object: a variable, a field on another object, an entry in a list.
An object becomes garbage once the program has no way left to reach it. How recently it was used makes no difference: an old object that something still refers to stays alive.
cat = {"name": "Tuna"}
cat = {"name": "Mochi"}
# The Tuna dict has no references left.
# Nothing can ever read it again: it is garbage.The search for reachable objects starts from what are called roots: local variables on the call stack, global and static variables, and a few things the runtime itself holds on to. Anything a root points to is alive, anything those objects point to is alive, and so on. Everything else can go.
Why memory needs cleaning up
Memory is finite. If unused objects are never removed, the heap keeps growing for as long as the program runs. At first the app just uses more RAM than it should. Then the operating system starts swapping memory to disk and everything slows down. Eventually an allocation fails and the program crashes with an out-of-memory error.
Wondering how this was made? How we make these