In Python, variables don't directly store values. Instead, they store references to objects in memory. Each object has a reference count, which keeps track of how many variables are pointing to it. When the reference count of an object becomes zero, it's considered garbage and is automatically collected by the garbage collector.
x = 10
y = x
print(id(x)) # Output: 140737469306640
print(id(y)) # Output: 140737469306640
In this example, both x
and y
refer to the same integer object with the memory address 140737469306640
. The reference count of this object is 2.
del x
print(id(y)) # Output: 140737469306640
After deleting x
, the reference count of the integer object becomes 1. Since y
is still pointing to it, the object is not garbage collected.
Garbage Collection:
Python's garbage collector periodically scans the memory for objects with a reference count of zero. These objects are marked as garbage and are reclaimed by the garbage collector. The exact timing and frequency of garbage collection can vary depending on the Python implementation and workload.