How does garbage collection happen in Python?

0 votes
I am new to Python. I want to know how does the garbage collection algorithm work in Python?
Jul 12 in Python by Neel
• 1,610 points
22 views

1 answer to this question.

0 votes

The Garbage collection runs automatically as the program is under execution, sometimes, we might want to run the Garbage collection at a specific time. We can do this by calling collect() function. Let’s try to define a LinkedList class to demonstrate this:

class LinkedList(object):
    def __init__(self, name):
        self.name = name
        self.next = None
    def set_next(self, next):
        print('Linking nodes %s.next = %s' % (self, next))
        self.next = next
    def __repr__(self):
        return '%s(%s)' % (self.__class__.__name__, self.name)

Once that is done, we can start constructing their objects and trigger Garbage collection manually:

# Constructing a circular LinkedList
a = LinkedList('1')
b = LinkedList('2')
c = LinkedList('3')
a.set_next(b)
b.set_next(c)
c.set_next(a)

# Remove references to the LinkedList nodes in this module's namespace
a = b = c = None

# Show the effect of garbage collection
for i in range(2):
    print('Collecting %d ...' % i)
    n = gc.collect()
    print('Unreachable objects:', n)
    print('Remaining Garbage:', pprint.pprint(gc.garbage))
    print

When we run this, the output will be:
python gc collect, python force garbage collection

In this example, the cyclic LinkedList objects are cleared as soon as garbage collection runs the first time.

answered Jul 12 by Arvind
• 1,530 points

Related Questions In Python

0 votes
1 answer

How does Python know whether a variable in the class is a method or a variable?

In python objects/variables are wrapped into methods ...READ MORE

answered Sep 18, 2018 in Python by ariaholic
• 7,320 points
37 views
0 votes
1 answer

How does insertion work in Python?

Or, this one: def ins_sort(k): ...READ MORE

answered Oct 8, 2018 in Python by charlie_brown
• 7,710 points
21 views
0 votes
1 answer

How does % work in Python?

The % (modulo) operator yields the remainder ...READ MORE

answered Oct 10, 2018 in Python by SDeb
• 12,360 points
16 views
0 votes
1 answer

How does slice notation in Python work?

The Python tutorial talks about it (scroll down a ...READ MORE

answered Oct 31, 2018 in Python by Priyaj
• 56,160 points
28 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 128 views
+1 vote
1 answer

How to install a module in Python 3.6 ?

If you are using Ubuntu then the ...READ MORE

answered Jun 25 in Python by Arvind
• 1,530 points
36 views
+1 vote
1 answer

How to convert records from csv to a list in Python?

If you are using Python 3.x then ...READ MORE

answered Jun 25 in Python by Arvind
• 1,530 points

edited Jun 26 by Kalgi 29 views