Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Garbage Collection in Python
Next article icon

Garbage Collection in Python

Last Updated : 08 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Garbage Collection in Python is an automatic process that handles memory allocation and deallocation, ensuring efficient use of memory. Unlike languages such as C or C++ where the programmer must manually allocate and deallocate memory, Python automatically manages memory through two primary strategies:

  1. Reference counting
  2. Garbage collection

Reference counting

Python uses reference counting to manage memory. Each object keeps track of how many references point to it. When the reference count drops to zero i.e., no references remain, Python automatically deallocates the object. Example:

Python
import sys  x = [1, 2, 3] print(sys.getrefcount(x))   y = x print(sys.getrefcount(x))   y = None print(sys.getrefcount(x)) 

Output
2 3 2 

Explanation:

  • x is referenced twice initially (once by x, once by getrefcount()).
  • Assigning y = x increases the count.
  • Setting y = None removes one reference.

Problem with Reference Counting

Reference counting fails in the presence of cyclic references i.e., objects that reference each other in a cycle. Even if nothing else points to them, their reference count never reaches zero. Example:

Python
import sys x = [1, 2, 3] y = [4, 5, 6]  x.append(y) y.append(x) print(sys.getrefcount(x)) print(sys.getrefcount(y)) 

Output
3 3 

Explanation:

  • x contains y and y contains x.
  • Even after deleting x and y, Python won’t be able to free the memory just using reference counting, because each still references the other.

Garbage collection for Cyclic References

Garbage collection is a memory management technique used in programming languages to automatically reclaim memory that is no longer accessible or in use by the application. To handle such circular references, Python uses a Garbage Collector (GC) from the built-in gc module. This collector is able to detect and clean up objects involved in reference cycles.

Generational Garbage Collection

Python’s Generational Garbage Collector is designed to deal with cyclic references. It organizes objects into three generations based on their lifespan:

  • Generation 0: Newly created objects.
  • Generation 1: Objects that survived one collection cycle.
  • Generation 2: Long-lived objects.

When reference cycles occur, the garbage collector automatically detects and cleans them up, freeing the memory.

Automatic Garbage Collection of Cycles

Garbage collection runs automatically when the number of allocations exceeds the number of deallocations by a certain threshold. This threshold can be inspected using the gc module.

Python
import gc print(gc.get_threshold()) 

Output
(2000, 10, 10) 

Explanation: It returns the threshold tuple for generations 0, 1 and 2. When allocations exceed the threshold, collection is triggered.

Manual garbage collection

Sometimes it’s beneficial to manually invoke the garbage collector, especially in the case of reference cycles. Example:

Python
import gc  # Create a cycle def fun(i):     x = {}     x[i + 1] = x     return x  # Trigger garbage collection c = gc.collect() print(c)  for i in range(10):     fun(i)  c = gc.collect() print(c) 

Output
0 10 

Explanation:

  • def fun(i) creates a cyclic reference by making a dictionary reference itself.
  • gc.collect() triggers garbage collection and stores the count of collected objects (initially 0).
  • for i in range(10) calls fun(i) 10 times, creating 10 cyclic references.
  • gc.collect() triggers garbage collection again and prints the count of collected cycles .

Types of Manual garbage collection

  • Time-based garbage collection: The garbage collector is triggered at fixed time intervals.
  • Event-based garbage collection: The garbage collector is called in response to specific events, such as when a user exits the application or when the application becomes idle.

Forced garbage collections

Python's garbage collector (GC) runs automatically to clean up unused objects. To force it manually, use gc.collect() from the gc module. Example:

Python
import gc  a = [1, 2, 3] b = {"a": 1, "b": 2} c = "Hello, world!"  del a,b,c gc.collect() 

Explanation:

  • del a, b, c deletes references to a, b and c, making them eligible for garbage collection.
  • gc.collect() forces garbage collection to free memory by cleaning up unreferenced objects.

Disabling garbage collection

In Python, the garbage collector runs automatically to clean up unreferenced objects. To prevent it from running, you can disable it using gc.disable() from the gc module. Example:

Python
import gc gc.disable()  gc.enable() 

Explanation:

  • gc.disable() disables automatic garbage collection.
  • gc.enable() re-enables automatic garbage collection.

Interacting with python garbage collector

A built-in mechanism called the Python garbage collector automatically eliminates objects that are no longer referenced in order to free up memory and stop memory leaks. The Python gc module offers a number of ways to interact with the garbage collector, which is often executed automatically.

1. Enabling and disabling the garbage collector: You can enable or disable the garbage collector using the gc. enable() and gc. disable() functions, respectively. Example:

Python
import gc  # Disable  gc.disable()  # Enable gc.enable() 

2. Forcing garbage collection: You can manually trigger a garbage collection using the gc. collect() function. This can be useful in cases where you want to force immediate garbage collection instead of waiting for automatic garbage collection to occur. Example:

Python
import gc  gc.collect() 

3. Inspecting garbage collector settings: You can inspect the current settings of the garbage collector using the gc.get_threshold() function, which returns a tuple representing the current thresholds for generations 0, 1, and 2. Example:

Python
import gc  t = gc.get_threshold() print(t) 

Output
(2000, 10, 10) 

4. Setting garbage collector thresholds: You can set the thresholds for garbage collection using the gc.set_threshold() function. This allows you to manually adjust the thresholds for different generations, which can affect the frequency of garbage collection. Example:

Python
import gc gc.set_threshold(500, 5, 5)  t = gc.get_threshold() print(t) 

Output
(500, 5, 5) 

Advantages and Disadvantages 

Let's explore some of the benefits and drawbacks of Python's garbage collection.

Advantages

Disadvantages

Automatic Memory Management

May introduce performance overhead

No Manual Memory Handling

Requires understanding of memory concepts

Efficient Cleanup via Generations

Limited control over timing of GC

Customizable GC Settings

Possibility of bugs or memory leaks


Next Article
Garbage Collection in Python

A

AFZAL ANSARI
Improve
Article Tags :
  • Python
  • python-basics
Practice Tags :
  • python

Similar Reads

    Python print() function
    The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
    2 min read
    Python – The new generation Language
    INTRODUCTION: Python is a widely-used, high-level programming language known for its simplicity, readability, and versatility. It is often used in scientific computing, data analysis, artificial intelligence, and web development, among other fields. Python's popularity has been growing rapidly in re
    6 min read
    Python Built in Functions
    Python is the most popular programming language created by Guido van Rossum in 1991. It is used for system scripting, software development, and web development (server-side). Web applications can be developed on a server using Python. Workflows can be made with Python and other technologies. Databas
    6 min read
    Python Dictionary Exercise
    Basic Dictionary ProgramsPython | Sort Python Dictionaries by Key or ValueHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPython program to find the sum of all items in a dictionaryPython program to find the size of a DictionaryWays to sort list of dicti
    3 min read
    Creating Your First Application in Python
    Python is one of the simplest and most beginner-friendly programming languages available today. It was designed with the goal of making programming easy and accessible, especially for newcomers. In this article, we will guide you through creating your very first Python application from a simple prin
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences