264

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Bnicholas
  • 13,671
  • 6
  • 23
  • 26
  • Possible duplicate of [Is there a way to delete created variables, functions, etc from the memory of the interpreter?](https://stackoverflow.com/questions/26545051/is-there-a-way-to-delete-created-variables-functions-etc-from-the-memory-of-th) – Richard Möhn Jan 28 '19 at 04:59

7 Answers7

485

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

pppery
  • 3,731
  • 22
  • 33
  • 46
starrify
  • 14,307
  • 5
  • 33
  • 50
  • 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. – Jakob Bowyer Nov 23 '11 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. – Philip Kearns Feb 18 '14 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 '14 at 17:15
  • Jakob Bowyer --I don't know what gc means. – Musixauce3000 Mar 30 '16 at 13:55
  • 2
    Garbage Collection/Collector/Collected – mccc Apr 12 '16 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 – hello_there_andy Nov 15 '16 at 22:30
  • @hello_there_andy What do you want to know? This I learnt by looking into how languages work. – Jakob Bowyer Nov 16 '16 at 09:10
  • 1
    This was the one I was looking for. Playing at the cmd line, I had ... `set = set(myList)` and then realized I could not use set anymore as a function (doh). Using `del set` allowed me to use it again as a fx. Of course I'd never use that reserved var in an actual script. – jbchurchill Jun 07 '17 at 13:08
  • To delete several variables, you can write: ```del var1, var2, var3``` – Haddock-san Apr 19 '21 at 11:49
181

What's wrong with self.left = None?

cs95
  • 379,657
  • 97
  • 704
  • 746
bnaul
  • 17,288
  • 4
  • 32
  • 30
  • 21
    Not familiar with the None keyword. Is this similar to null in other languages? – Bnicholas Nov 23 '11 at 05:41
  • 7
    Yes; it is equivalent to null. – Smashery Nov 23 '11 at 05: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 '11 at 05:57
  • It's not a keyword; it's a set-by-default name for a built-in object. You can do anything with `None` that you can do with any other "plain" object of unspecified type: store it in containers, print a string representation of it, check some metadata on it... Anyway, did you try Google for "python null equivalent"? I'm serious; it will take a bit of analysis, but the information is right there. – Karl Knechtel Nov 23 '11 at 12:11
  • 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. – Musixauce3000 Mar 30 '16 at 13:52
  • @Robino Me too. But I suppose that's the search engine's issue for misinterpreting my intent, not OP's or SO's. – flow2k Dec 12 '18 at 19:17
  • Lol sometimes you just over think lot of things to make it complicated. – StackPointer Dec 28 '18 at 22:58
  • 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 '19 at 20:53
  • @bnaul because it still takes up memory, it just doesn't have value, also, if you try accessing it, after setting it to None, it doesn't give an error. –  Oct 02 '19 at 00:36
132

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.

user11788
  • 1,675
  • 1
  • 12
  • 6
  • 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. – Tedo Vrbanec Jan 19 '19 at 17:17
71

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
Viraj Shah
  • 990
  • 8
  • 8
  • 10
    I don't understand why the =None answer is so popular. This is the correct answer – Nikolay Gromov Oct 09 '15 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. – user1767754 Jan 18 '18 at 09: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 '18 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 ? – Pierre.Sassoulas Jan 23 '19 at 10:02
  • Check `gcore $PID`, your variable still exists in memory. – SurpriseDog Jun 20 '21 at 20:23
50
  • 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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
5

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

variable = None; del variable
Umair Ayub
  • 19,358
  • 14
  • 72
  • 146