(I already answered the question in the other question of yours, so I'm going to use it here as well, with slight modifications:)
del
does not delete objects; in fact in Python, it is not even possible to tell the interpreter/VM to remove an object from memory because Python is a garbage collected language (like Java, C#, Ruby, Haskell etc).
Instead, what del
does when called on a variable (as opposed to a dictionary key or list item) like this:
del a
is that it only removes the local (or global) variable not what it points to (every variable in Python holds a pointer/reference to its contents not the content itself). In fact, since locals and globals are stored as a dictionary under the hood (see locals()
and globals()
), del a
is equivalent to:
del locals()['a']
(or del globals()['a']
when applied to a global.)
so if you have:
a = []
b = a
you're making a list, storing a reference to it in a
and then copying that reference into b
without copying/touching the list object itself. Therefore these two calls affect one and the same object:
>>> a.append(1)
>>> b.append(2)
>>> a
[1, 2]
>>> b
[1, 2]
>>> a is b # would be False for 2 identical but different list objects
True
>>> id(a) == id(b)
True
(id
returns the memory address of an object)
whereas deleting b
is in no way related to touching what b
points to:
>>> a = []
>>> b = a
>>> del b # a is still untouched and points to a list
>>> b
NameError: name 'b' is not defined
>>> a
[]
del
does. It doesn't delete objects, and it didn't need a new tag to begin with. – Hoenir