265

Is there a way to clear the value of a variable in python?

For example if I was implementing a binary tree:

class Node:
    self.left = somenode1
    self.right = somenode2

If I wanted to remove some node from the tree, I would need to set self.left to empty.

1

7 Answers 7

483

The del keyword would do.

>>> a=1
>>> a
1
>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

But in this case I vote for self.left = None

9
  • 23
    sometimes this doesn't remove it entirely this only removes that reference to a in memory. This can leave ghost variables in memory that don't get gc. Nov 23, 2011 at 10:30
  • 8
    del also has the disadvantage that if you try to delete a variable that doesn't exist it throws an exception, which is usually undesirable. Feb 18, 2014 at 11:46
  • 37
    I just wanted to point out that if you accidentally declared a variable that is overwriting built in commands e.g., type=… when you meant to type type(…) then deleting it is the easiest way to get back the original functionality. That is, if you keep it around as None you will still be cutting off access to the underlying function.
    – mpacer
    Jul 14, 2014 at 17:15
  • 2
    Garbage Collection/Collector/Collected
    – mccc
    Apr 12, 2016 at 14:11
  • 1
    @JakobBowyer May I ask how you know this? Reading this makes me quite paranoid about how many other importances in programming are still unknown-unknowns to me Nov 15, 2016 at 22:30
180

What's wrong with self.left = None?

9
  • 21
    Not familiar with the None keyword. Is this similar to null in other languages?
    – Bnicholas
    Nov 23, 2011 at 5:41
  • 7
    Yes; it is equivalent to null.
    – Smashery
    Nov 23, 2011 at 5:44
  • 13
    @Bnicholas However it's not like null in PHP, in that setting a variable to null in PHP gives you similar behaviour in most cases as if you hadn't defined it in the first place. A value of None in Python is quite different from an undefined variable. None is quite like most other incarnations of null, however (until we get into more arcane details, at least).
    – Ben
    Nov 23, 2011 at 5:57
  • 24
    Open the python terminal and type print x and press enter. This will produce an interpreter error, as do most languages when you try to print an undefined variable. But if you define the variable, and then try to clear it with None, using the print x code will produce the word None as output. I'm new to python so I could be mistaken, but this does not seem like the behavior of a cleared variable. Mar 30, 2016 at 13:52
  • 3
    This solution isn't the best solution. It just assigns it as null, but it still is a variable. If you were to overwrite keywords - then you would still get errors trying to call a none type. Use del variable
    – Dustin K
    Aug 21, 2019 at 20:53
133

var = None "clears the value", setting the value of the variable to "null" like value of "None", however the pointer to the variable remains.

del var removes the definition for the variable totally.

In case you want to use the variable later, e.g. set a new value for it, i.e. retain the variable, None would be better.

1
  • What if I want to completely delete variable that in some circumstances does not exist. Is there any parameter to avoid an error? I need to delete several variables: del a, b, c, d I could use loop and try/except, but I prefer some switch to avoid it. Jan 19, 2019 at 17:17
72

Actually, that does not delete the variable/property. All it will do is set its value to None, therefore the variable will still take up space in memory. If you want to completely wipe all existence of the variable from memory, you can just type:

del self.left
5
  • 10
    I don't understand why the =None answer is so popular. This is the correct answer Oct 9, 2015 at 13:30
  • 1
    The OP said clear not remove. del will kill the attribute and lookups. It is way cleaner to set it to None, than you can check if self.left and that would be good enough to check if a node is empty. Jan 18, 2018 at 9:06
  • 1
    "It is way cleaner to set it to None" -- it's worth considering that if someone (yourself some time later or a collaborator) is reading the code del, IMHO, makes it more obvious that the variable can be forgotten about when 'mentally parsing' the code.
    – Pocketsand
    May 27, 2018 at 17:52
  • 1
    @NikolayGromov in your day to day code, when you want to get the value of self.left do you prefer to check if self.left:, or do you prefer to deal with a possible NameError exception that will crash your program if you don't handle it everywhere ? Jan 23, 2019 at 10:02
  • Check gcore $PID, your variable still exists in memory. Jun 20, 2021 at 20:23
49
  • If want to totally delete it use del:

    del your_variable
    
  • Or otherwise, to make the value None:

    your_variable = None
    
  • If it's a mutable iterable (lists, sets, dictionaries, etc, but not tuples because they're immutable), you can make it empty like:

    your_variable.clear()
    

Then your_variable will be empty

0
5

Do you want to delete a variable, don't you?

ok, I think I've got a best alternative idea to @bnaul's answer:

You can delete individual names with del:

del x

or you can remove them from the globals() object:

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.

Modules you've imported (like import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.

5

Delete its contents by setting it to None and then del to remove its pointer from memory

variable = None; del variable

Not the answer you're looking for? Browse other questions tagged or ask your own question.