#6 – Memory Management in Python Flashcards
(11 cards)
How is memory managed in Python?
Memory is managed automatically using reference counting and garbage collection.
What is reference counting in Python?
Every object has a counter of how many references point to it. When the count reaches zero, the object is deleted.
What is garbage collection in Python?
Garbage collector removes objects with circular references that are no longer accessible.
How do you check the reference count of an object?
Use sys.getrefcount()
.
import sys x = [] print(sys.getrefcount(x))
How do you manually run the garbage collector?
Use the gc
module.
import gc gc.collect()
What is a memory leak in Python?
When objects are unintentionally kept alive, causing memory usage to grow.
What causes circular references?
When two or more objects reference each other, preventing automatic deletion by reference counting.
What is del
used for in memory management?
It deletes a reference to an object. If it’s the last one, the object is garbage collected.
Do you always need to use del
?
No, but you might use it to free large objects early or in tight loops.
How can context managers help with memory?
They ensure resources like files and connections are properly closed.
with open('file.txt') as f: data = f.read()
How can you investigate memory usage in Python?
Use libraries like tracemalloc
, psutil
, or objgraph
for memory tracking and debugging.