Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How are variables stored in Python (Stack or Heap)?
In Python, variables are stored differently based on their type and scope in two main memory regions: the stack and the heap. Python, being a high-level programming language, abstracts away many low-level memory management details from the programmer. However, understanding how variables are stored is essential for writing efficient and optimized code.
In this article, we will explore how variables are stored in Python and the difference between stack and heap memory allocation.
Stack Memory
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 strings. These variables have a predictable memory footprint and are stored directly on the stack for quick access.
Example 1: Local Variables on Stack
Let's see how local variables are stored on the stack ?
def example_function():
x = 5
y = True
z = 'Hello'
print(f"x = {x}, y = {y}, z = {z}")
example_function()
x = 5, y = True, z = Hello
In this example, variables x, y, and z are local variables within example_function(). They are stored on the stack, and when the function execution completes, they are automatically removed from the stack.
Example 2: Function Parameters and Return Values
def calculate_sum(a, b):
result = a + b
return result
x = 5
y = 3
sum_result = calculate_sum(x, y)
print(f"Sum result: {sum_result}")
Sum result: 8
Here, variables x and y are integers stored on the stack. When calculate_sum() is called, the local variable result is also stored on the stack. Once the function completes, local variables are removed from the stack.
Heap Memory
The heap is a region of memory used for dynamic memory allocation. It stores objects and data structures that can vary in size during runtime. For non-primitive data types, the variable reference is stored on the stack, while the actual object data is stored on the heap.
When we create variables of non-primitive data types (lists, dictionaries, custom objects), the variable reference is stored on the stack, while the object's data is stored in heap memory. The reference on the stack points to the actual object in the heap.
Example 3: Objects on Heap
def create_data():
my_list = [1, 2, 3, 4]
my_dict = {'name': 'Python', 'type': 'language'}
return my_list, my_dict
data_list, data_dict = create_data()
print(f"List: {data_list}")
print(f"Dictionary: {data_dict}")
List: [1, 2, 3, 4]
Dictionary: {'name': 'Python', 'type': 'language'}
In this example, my_list and my_dict are references stored on the stack, but the actual list and dictionary objects are stored on the heap. Multiple variables can reference the same object on the heap.
Memory Allocation Comparison
| Memory Type | Storage | Access Speed | Data Types |
|---|---|---|---|
| Stack | Local variables, references | Fast | Primitive types, references |
| Heap | Object data | Slower | Lists, dicts, custom objects |
Garbage Collection
Python uses automatic garbage collection to manage heap memory. It identifies and frees memory occupied by objects that are no longer reachable or referenced by any variable, ensuring efficient memory usage without manual intervention.
import gc
# Create objects
data = [1, 2, 3, 4, 5]
reference = data
# Remove reference
data = None
print("Reference count before:", len(gc.get_referrers(reference)))
# Force garbage collection
gc.collect()
print("Garbage collection completed")
Reference count before: 1 Garbage collection completed
Conclusion
Python variables are stored differently based on their type and scope. Primitive data types use efficient stack storage, while complex objects store references on the stack and data on the heap. Understanding this memory model helps in writing more efficient Python code and better memory management.
