Marco Sulla wrote:
I can be wrong, but for what I know, del variable_name does not optimize the code, in the sense of performance.
Correct, by itself `del variable_name` does not optimize the code - however, there exist functions implemented in C (which I gave examples of) with special cases for when `sys.getrefcount(x) == 1`, which means they are free to repurpose an existing object.
allowing the gc to free the memory if that variable was the last reference to the object.
The gc may not be relevant here - in CPython, objects are cleaned up immediately as part of reference counting. The GC only kicks in for circular object graphs.
In a for and a list comprehension, I suppose it's unneeded, since the variable points automatically to another memory location, so the reference is removed automatically.
The nth reference is not removed until the n+1th reference has been created. This is unavoidable in a for loop without breaking existing code, but I think could (and should?) be changed in a list comprehension
Furthermore, if you want to delete a temporary variable, you could do:
bc = b * c a = bc + d del bc
This doesn't hit the optimization I was talking about, because `ndarray.__add__(bc, d)` contains `if sys.getrefcount(self) == 1`, but here the local variable results in a second refcount.