Category: python
Automatic Memory Management
Published on 27 Oct 2026
Explanation
Python manages object allocation and reclamation automatically. References and scope influence object lifetime.
Code:
values = [10, 20, 30] print(values) del values
Explanation
An object remains accessible while references keep it alive; deleting one name does not remove other references.
Code:
class Student:
def __init__(self, name): self.name = name
student = Student('Arun')
backup = student
del student
print(backup.name)
Explanation
In CPython, reference counting handles many objects while cyclic garbage collection detects many unreachable reference cycles.
Code:
import gc print(gc.isenabled()) print(gc.get_count()) print(gc.collect())
Explanation
Objects can refer to one another in cycles. CPython's cyclic collector can reclaim unreachable cycles.
Code:
class Node: pass a = Node(); b = Node() a.other = b; b.other = a del a, b
Explanation
Use context managers for deterministic cleanup of files, sockets, and similar resources rather than relying on garbage collection.
Code:
with open('example.txt', 'w', encoding='utf-8') as file:
file.write('Hello Python')
print('File closed after block')