![]() |
VOOZH | about |
Memory management refers to process of allocating and deallocating memory to a program while it runs. Python handles memory management automatically using mechanisms like reference counting and garbage collection, which means programmers do not have to manually manage memory.
Let's explore how Python automatically manages memory using garbage collection and reference counting.
It is a process in which Python automatically frees memory occupied by objects that are no longer in use.
For more information, refer to Garbage Collection in Python
It is one of the primary memory management techniques used in Python, where:
Example:
140645192555456 140645192555456 [1, 2, 3, 4]
Explanation:
Now that we know how references work, let’s see how Python organizes memory.
It is the process of reserving space in a computer’s memory so that a program can store its data and variables while it runs. In Python, this process is handled automatically by interpreter, but the way objects are stored and reused can make a big difference in performance.
Let's see an example to understand it better.
Python applies an internal optimization called object interning for small immutable objects (like integers from -5 to 256 and some strings). Instead of creating a new object every time, Python reuses same object to save memory.
Suppose:
x = 10
y = 10
Here, Python does not create two separate objects for 10. Instead, both x and y point to the same memory location. Let's verify if it's true:
x and y refer to same object
Now, if we change x to a different integer:
x and y do not refer to the same object
When x is changed, Python creates a new object (11) for it. The old link with 10 breaks, but y still refers to 10.
👁 memory-allocation-python-3In Python, memory is divided mainly into two parts:
Both play different roles in how variables and objects are stored and accessed.
Stack memory is where method/function calls and reference variables are stored.
In simple terms: Stack memory is temporary and is only alive until the function or method call is running.
How it Works:
Example:
Here a, b and c are stored in stack memory when function func() is called. As soon as function ends, this memory is released automatically.
Heap memory is where actual objects and values are stored.
In simple terms: Heap memory is like a storage area where all values/objects live and stack memory just keeps directions (references) to them.
How it Works:
Example:
Explanation: Here, list [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] is stored in heap memory. The variable a in stack memory just holds a reference pointing to this list in the heap.