When am I supposed to use del in python?
<p>So I am curious lets say I have a class as follows</p>

<pre><code>class myClass:
    def __init__(self):
        parts = 1
        to = 2
        a = 3
        whole = 4
        self.contents = [parts,to,a,whole]
</code></pre>

<p>Is there any benifit of adding lines </p>

<pre><code>del parts
del to
del a
del whole
</code></pre>

<p>inside the constructor or will the memory for these variables be managed by the scope?</p>

<p>Never, unless you are very tight on memory and doing something very bulky. If you are writing usual program, garbage collector should take care of everything.</p>

<p>If you are writing something bulky, you should know that <code>del</code> does not delete the object, it just dereferences it. I.e. variable no longer refers to the place in memory where object data is stored. After that it still needs to be cleaned up by garbage collector in order for memory to be freed (that happens automatically).</p>

<p>There is also a way to force garbage collector to clean objects - <code>gc.collect()</code>, which may be useful after you ran <code>del</code>. For example:</p>

<pre><code>import gc
a = [i for i in range(1, 10 ** 9)]
...
del a
#  Object [0, 1, 2, ..., 10 ** 9 - 1] is not reachable but still in memory
gc.collect()
#  Object deleted from memory
</code></pre>

<hr>

<p><strong>Update</strong>: really good note in comments. Watch for other references to the object in memory. For example:</p>

<pre><code>import gc
a = [i for i in range(1, 10 ** 9)]
b = a
...
del a
gc.collect()
</code></pre>

<p>After execution of this block, the large array is still reachable through <code>b</code> and will not be cleaned.</p>

python memory-management