Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between setting a variable to None or deleting it? [duplicate]

Is there a noticeable difference in performance or memory if you clear variables by setting

x = 'something'
x = None

as opposed to

x = 'something'
del x

for many variables?

like image 760
cshin9 Avatar asked Mar 18 '16 14:03

cshin9


1 Answers

Setting a variable to None or deleting it both causes the reference to the object x to be released. The main difference is that with x = None the name x still exists, even though it's now pointing to a different object (None). When using del the name is deleted as well.

For the garbage collector, there is no difference. del does not force any garbage collection of the referenced object.

Edit: as @Viroide pointed out, using del causes an exception to be thrown when trying to call the variable x.

like image 56
Lars de Bruijn Avatar answered Oct 19 '22 05:10

Lars de Bruijn