The del statement doesn’t actually delete objects
To understand this, you need to know a little bit about how Python handles variables and assignment.
Objects, references, and the = operator
<variable-name> = <object>The assignment statement has 3 parts
- The variable name.
- The object being assigned to the variable.
- The = operator, which creates a reference from the variable name to the object.
<variable-name> ⇒ <object>This emphasizes the fact that variables don’t contain objects, they refer to objects.
If I assign the same object to two variables, they each contain a reference to that object.
Then if I delete the "X" variable here’s what happens
Clearly, the int(29) object didn’t get deleted. You know that because you can still refer to it through the "Y" variable. It was the reference from X to 29 that got deleted. And because you can’t have a variable that doesn’t refer to anything, the variable “X” also got deleted.
So how do you delete an object?
Well, you really can’t. Python does something called “reference counting”. It keeps track of how many references exist to an object. When the number of references drops to zero, the object is marked for “garbage collection”. Exactly how and when garbage collection happens is outside your control.