How are variables stored in Python (Stack or Heap)?


In Python, variables are stored differently based on their type and scope either it can be stored in the heap or in the stack which are the two main memory regions utilized for a variable storage. Python, being a high-level programming language, abstracts away many low-level memory management details from the programmer. However, it's still essential to understand how variables are stored in Python to write efficient and optimized code.

In this article we will see How are variables stored in Python (Stack or Heap).

Stack

The stack is a region of memory used for storing local variables and function call information. It operates on a Last-In-First-Out (LIFO) basis, where the most recently added item is the first to be removed.

The stack is generally used for variables of primitive data types, such as numbers, booleans, and characters. These variables have a fixed memory size, which is known at compile-time.

Let us look at an example to illustrate how variables of primitive types are stored on the stack −

Program example 1

def example_function():
   x = 5
   y = True
   z = 'Hello'
   # Some code...

example_function()

In the above example, variables named x, y, and z are local variables within the function named example_function(). They are stored on the stack, and when the function execution completes, they are automatically removed from the stack.

Let us see one more example of how variables are stored in the Stack −

Program example 2

def calculate_sum(a, b):
   result = a + b
   return result

x = 5
y = 3
sum_result = calculate_sum(x, y)

In the above example, the variables x and y are integers, which are primitive data types. They are stored directly on the stack. When the calculate_sum() function is called, the local variable result is also stored on the stack. Once the function execution completes and the return value is obtained, the local variables are removed from the stack.

Heap

The heap is a region of memory used for dynamic memory allocation. It is where objects and data structures, which are variables of non-primitive types, are stored. Objects on the heap have a more complex structure and can vary in size. The stack stores the reference to the object on the heap, while the actual data of the object is stored in the heap.

Whenever we create variables of non-primitive data types( for example lista, custom objects pr dictionaries), the variable itself(reference) is stored on the stack, while on the other hand the object’s data is stored on the heap memory. The reference on the stack points to the actual object that is present on the heap memory.

Let us look at an example to illustrate how variables are stored on the heap −

Program example 3

def example_function():
   my_list = [1, 2, 3]
   # Sample code…
example_function()

In the above example, the variable my_list is a reference to the actual list object stored on the heap. The reference is stored on the stack. When the create_list() function is called, memory is allocated for the list object on the heap, and the reference to that memory location is stored on the stack. The result_list variable outside the function also holds a reference to the same list object on the heap.

It's important to note that even though the reference is stored on the stack, the actual data (the list elements in this case) is stored on the heap. Multiple variables can reference the same object on the heap.

It can be more efficient if we are storing primitive data types on the stack due to their fixed sie and simple data structure. On the other hand, storing objects on the heap memory provides flexibility and allows for the dynamic memory allocation.

In Python, the memory management and variable storage might differ across different implementations or version sof the language. Depending upon how variables are stored can be influenced by factors such as the what python interepreter is there, underlying Operating systems, and the memory management strategy employed.

Garbage collection

Garbage collection in Python is an automatic memory management process. It identifies and frees up memory occupied by objects that are no longer reachable or referenced by any variable, ensuring efficient memory usage and eliminating the need for manual memory deallocation by the programmer.

For example: if there is a reference variable that is not pointing to any of the objects in the memory that means it is not in use, then comes a garbage collector which is there in the virtual machine that automatically deletes that particular reference variable from the heap memory.

Conclusion

In conclusion, python variables are stored differently based on the type or the scope of the variable. If the variable is of primitive data type then that variable is stored on the stack which offers efficient memory allocation for the fixed-sized variables. On the other hand, if the variable is of non-primitive data types, like objects or the data structures, which store the reference on the stack and the object’s data on the heap memory. Having a brief understanding of the heap and stack memory is important for memory management and designing efficient Python code that leverages the strengths of both the stack and the heap.

Updated on: 24-Jul-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements