Search code examples
pythonappenddel

Why doesn't del do the same thing?


Why does the following code change both variables:

>>> a = []
>>> b = a
>>> a.append(9)
>>> a
[9]
>>> b
[9]
>>> 

But the del statement does not achieve the same effect?

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

Solution

  • When you do:

    a = b
    

    What you're doing is assigning the label b to the same object that the label a is refering to.

    When you do:

    a.append(9)
    

    You're adding 9 to the list object pointed to by both a and b. It's the same object, so they show the same result.

    When you do:

    del a
    

    You're deleting the reference to the object, not the object itself. If it's the only reference, then the object will be garbage collected. But in your case, there's another reference - b - so the object continues to exist.