2

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?

3
  • Is this out of curiosity or need? There's probably an answer, but I think there are better routes to take if you're trying to make the loop faster. Commented Aug 1, 2020 at 11:03
  • then what is the use of loop here? Commented Aug 1, 2020 at 11:03
  • See nedbatchelder.com/text/names.html . Short answer: you are only removing a name, so it doesn't change anything here. You just lost a tiny bit of time... Commented Aug 1, 2020 at 11:06

1 Answer 1

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:

https://nedbatchelder.com/text/names.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.