Open In App

How are variables stored in Python – Stack or Heap?

Last Updated : 30 Jan, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Memory allocation can be defined as allocating a block of space in the computer memory to a program. In Python memory allocation and deallocation method is automatic as the Python developers created a garbage collector for Python so that the user does not have to do manual garbage collection.

Garbage Collection

Garbage collection is a process in which the interpreter frees up the memory when not in use to make it available for other objects.
Assume a case where no reference is pointing to an object in memory i.e. it is not in use so, the virtual machine has a garbage collector that automatically deletes that object from the heap memory

Note: For more on garbage collection you can refer to this article.

Reference Counting

Reference counting works by counting the number of times an object is referenced by other objects in the system. When references to an object are removed, the reference count for an object is decremented. When the reference count becomes zero, the object is deallocated.

For example, Let’s suppose there are two or more variables that have the same value, so, what Python virtual machine does is, rather than creating another object of the same value in the private heap, it actually makes the second variable point to that originally existing value in the private heap. Therefore, in the case of classes, having a number of references may occupy a large amount of space in the memory, in such a case referencing counting is highly beneficial to preserve the memory to be available for other objects

Example:




# Literal 9 is an object 
b = 9
a = 4
    
# Reference count of object 9  
# becomes 0 and reference count
# of object 4 is incremented
# by 1
b = 4


Memory Allocation in Python

There are two parts of memory:

  • stack memory
  • heap memory

The methods/method calls and the references are stored in stack memory and all the values objects are stored in a private heap.

Work of Stack Memory

The allocation happens on contiguous blocks of memory. We call it stack memory allocation because the allocation happens in the function call stack. The size of memory to be allocated is known to the compiler and whenever a function is called, its variables get memory allocated on the stack.

It is the memory that is only needed inside a particular function or method call. When a function is called, it is added onto the program’s call stack. Any local memory assignments such as variable initializations inside the particular functions are stored temporarily on the function call stack, where it is deleted once the function returns, and the call stack moves on to the next task. This allocation onto a contiguous block of memory is handled by the compiler using predefined routines, and developers do not need to worry about it.

Example:




def func():
      
    # All these variables get memory 
    # allocated on stack 
    a = 20
    b = []
    c = ""


Work of Heap Memory

The memory is allocated during execution of instructions written by programmers. Note that the name heap has nothing to do with heap data structure. It is called heap because it is a pile of memory space available to programmers to allocated and de-allocate. The variables are needed outside of method or function calls or are shared within multiple functions globally are stored in Heap memory.

Example:




# This memory for 10 integers 
# is allocated on heap. 
a = [0]*10 




Similar Reads

Merge PDF stored in Remote server using Python
Prerequisites: Working with PDF files in Python There are many libraries for manipulating PDF files in Python but all are using when that all PDF files already downloaded in your local machine. But what if your target PDF files are in Remote server, you have only URLs of files and no required download in your machine or compute server. Here We will
2 min read
Retrieve Image and File stored as a BLOB from MySQL Table using Python
Prerequisites: MySQL server should be installed In this post, we will be talking about how we can store files like images, text files, and other file formats into a MySQL table from a python script. Sometimes, just like other information, we need to store images and files into our database and provide it the security equivalent to other data. In My
3 min read
Execute PostgreSQL Stored Procedure and Function in Python
A stored procedure is a sequence of structured procedural language queries stored in a relational database management system as a data dictionary, which can be shared and reused multiple times. All CRUD operations, querying operations can be performed by calling the stored procedure. The use of stored procedures reduces the repetition of code that
3 min read
Sum Integers Stored in JSON using Python
Summing integers stored in JSON using Python involves reading JSON data, parsing it, and then calculating the sum of integer values. Python's json module is instrumental in loading JSON data, and the process often includes iterating through the data structure to identify and accumulate integer values. In this context, a common scenario is a JSON fi
4 min read
PyQt5 ComboBox – User entered items not stored in drop down menu
In this article we will see how user entered item don't get added in the combo box i.e when user insert item in the editable combo box it do not get inserted at the any position of the drop down list, by default when user insert any item it get inserted at the bottom.If we use normal i.e non editable combo box user is not able to add any item to th
2 min read
Numpy: Index 3D array with index of last axis stored in 2D array
NumPy, or Numerical Python, is a powerful library for efficient numerical computation in Python. One of the key features of NumPy is its ability to perform advanced indexing, which allows to access and manipulate specific elements of an array based on complex conditions. In this article, we will explore how to index a 3D array using a 2D array of i
5 min read
Heap queue (or heapq) in Python
Heap data structure is mainly used to represent a priority queue. In Python, it is available using the "heapq" module. The property of this data structure in Python is that each time the smallest heap element is popped(min-heap). Whenever elements are pushed or popped, heap structure is maintained. The heap[0] element also returns the smallest elem
7 min read
Python Code for time Complexity plot of Heap Sort
Prerequisite : HeapSort Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. We implement Heap Sort here, call it for different sized random lists, meas
3 min read
Min Heap in Python
A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2 for 0 based indexing and for 1 b
5 min read
Max Heap in Python
A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored a index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2. Examples of Max Heap : How is Ma
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg