Memory Allocation

As responsible programmers, we are aware that when allocating memory space for variables, we are borrowing system resources, and eventually, we will have to return that which we borrowed back to the system. Happily, not only do we not have to explicitly allocate the memory, we don’t have to deallocate it either. That is memory management made easy. Well, okay, perhaps it had something to do with the decision that Python should simply be a tool for the application writer to and shouldn’t have to worry about lower-level, operating system or machine-oriented tasks.

Garbage Collection

Memory that is no longer being used is reclaimed by the system using a mechanism known as garbage collection. Python’s garbage collector will automatically deallocate a data object once is it no longer needed, all without requiring any management on the programmer’s part. How does Python decide when an object is “no longer needed?” By keeping track of the number of references to objects. This is called reference counting.

Reference Counting

To keep track of memory that has been allocated, Python does something quite similar to card-counting, a popular scheme used in casino gaming. When an object is created, a reference is made to that object. An internal tracking variable, a reference counter, keeps track of how many references are being made to each object. The reference count for an object is initially set to one (1) when an object is created and (its reference) assigned.
 
New references to objects, also called aliases, occur when additional variables are assigned to the same object, passed as arguments to invoke other bodies of code such as functions, methods, or class instantiation, or assigned as members of a sequence or mapping.