How does Python manage memory?

Python manages memory automatically. All objects live in a private heap, and Python frees them when they are no longer needed. It uses two ideas for this:

  • Reference counting: every object keeps a count of how many names point to it. When the count becomes zero, the memory is freed at once.
  • Garbage collector: finds groups of objects that point to each other (cycles) and are no longer used, which reference counting cannot free. It is available in the gc module.
import sys

a = [1, 2, 3]
b = a
print(sys.getrefcount(a))

Output:

Tutorials Class - Output Window

3

The count is 3 because of a, b and the temporary reference made while calling getrefcount(). You do not free memory yourself in Python, but you should avoid keeping big objects alive longer than needed.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.