alextm
alextm

Reputation: 25

Should I delete variables I don't plan on using anymore?

At first, it sounds like a no-brainer, but the more I think about it the more I feel like others' opinions would be helpful. Whenever looking at others' Python code, I never see them delete variables. Is there a reason for this, or is it just them not wanting to. I assume it has to do more with clean code vs. quick code, but I'm not sure that's the case. Plus, to be honest, I don't know for sure the impact deleting variables has on a program (I always just assumed it was good, since the courses I've taken on Python never really mentioned it).

Example of deleting a variable...

j = 'jjjjj'
for i in range(len(j)):
    print(j[i], j)
del j

Not the most relatable example but you get the point.

Upvotes: 1

Views: 4106

Answers (1)

Jay
Jay

Reputation: 2946

In general, don't worry about deleting variables.

Python has garbage collection, so any objects that you can no longer access (usually because you've left their scope) will automatically be freed from memory, you don't have to worry about this at all.

The case where you might want to use del would be if you want to make it explicity clear that this variable cannot be used anymore by this part of the program.

As mentioned in the comments, this won't even necessarily delete your object.

You can read about the del keyword more here

Upvotes: 5

Related Questions