Does deleting a variable in python for loop make it more memory efficient?

by wowzaaa   Last Updated August 01, 2020 11:26 AM - source

Let's say that I have a variable in which I will use for a loop 1000 times such that:

A = [3,4,5,6]
for i in range(1000):
    # if something
    # c = <a list which length depends on runtime>
    A = c
    del c

Would deleting c after single loop makes memory consumption more efficient?

Tags : python list loops del

Answers 1

In general, no. It doesn't.

del deletes names from namespaces, not objects.

Of course, if you remove a reference, and the reference count reaches 0, the object will be reclaimed (immediately in CPython).

But note, in your loop above, you create another reference anyway, A = c, so it definitely doesn't help at all.

There is one scenario where this may be beneficial, suppose you do this in a global scope, e.g. at a module level, so not in a function. Because python for-loops don't create their own scopes, c has now remained in the global namespace, and potentially, it keeps a giant list alive until the end of the program.

This is usually better solved by organizing your program better into modular functions, and only creating references to objects in the global scope that you want to survive until the end of the program. However, sometimes, you do end up doing a loop like that, and in that case, explicitly removing that last reference does help (but again, since you did A = c, then it wouldn't help anyway).

I feel that you have a fundamental misunderstanding of how Python variables work. I second the suggestion from the comments to read:

August 01, 2020 11:20 AM

Related Questions

list comprehension variable assignment

Updated March 16, 2019 19:26 PM

How to expand this nested list comprehension in Python

Updated October 15, 2018 23:26 PM