Python Memory Management

In this article we learn about python memory management, about how python allocates and deallocates the memory and tells about efficient memory usage to write an optimized code. Here we learn about python memory management techniques such as garbage collection, Reference counting, memory allocation and deallocation, optimization techniques.

Introduction

It is important to learn python memory management to understand how the language handles memory allocation and deallocation.

let’s see how memory management works

  • In Python, we don’t need to declare the type of variable(it a name in which we store the values), the interpreter keeps track of the types internally. This dynamic typing help interpreter to track the variables. Let’s see an example :
x = 10
print(x)

Output: 10

  • Python memory manager uses a private heap space, this private heap space store objects and values in it.
  • Reference counting is a simple and efficient memory management strategy. Reference counting will track how frequently a program uses an object. Object is a variable which stores the data and interacts directly with python libraries and frameworks by giving instructions to run the program.
  • Garbage Collection handles cyclic references. Cyclic references occur when two or more objects reference each other, forming a loop of references. It will try to release unused objects by removing them from the program’s memory.
  • Memory Allocation is a allocation utilizes a private heap space, which is a portion of the computer’s memory dedicated to python interpreter.
  • Python Memory deallocation is deallocation of memory automatically done by Python interpreter.
  • click here for more details
  • In Python Adding elements to an array

Memory Management Example in Python

let’s see how memory management is done in lists and tuples using python

  • Memory allocation and deallocation in Lists and tuples.
  • allocation in lists
#python memory management in Lists
list1 = [11, 12, 13]
print("list1 =",list1)
#inserting values into list1
list1.append(14)
list1.append(15)
#printing final values of list1
print("Final list1 =",list1)

above code Output:

list1 =[11, 12, 13] 
Final list1 =[11, 12, 13, 14, 15]
  • deallocation in list
#python memory management
list1 = [3,4,5,6,7]
print("list ="list1)
#to delete elements from list
list1.remove(4)
list1.remove(5)
#printing of new tuple
print("new list =",list1)

Deallocation Output:

list =[3,4,5,6,7]

new list =[3,6,7]
  •  allocation in tuple 

 

#memory allocation in tuples
Tuple1 = (22, 33, 44)
#printing of tuple
print("Tuple =",Tuple1)

Output:

Tuple =(22, 33, 44)
  • There is no deallocation in tuple

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top