Search code examples
pythonpython-3.xreferencedel

Variable Containing Reference to a List but When Referenced List Deleted?


From what I understand, assigning a list variable to a variable will create a reference like a pointer in C.

>>> l1 = ['joe biden', 'donald trump', 'justin trudeau']
>>> l2 = l1
>>> l1
['joe biden', 'donald trump', 'justin trudeau']
>>> l2
['joe biden', 'donald trump', 'justin trudeau']
>>> l1.append('barack obama')
>>> l1
['joe biden', 'donald trump', 'justin trudeau', 'barack obama']
>>> l2
['joe biden', 'donald trump', 'justin trudeau', 'barack obama']
>>> 

this is expected.

but here is the thing:

>>> del l1
>>> l1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'l1' is not defined
>>> l2
['joe biden', 'donald trump', 'justin trudeau', 'barack obama']
>>> l1.append('obama')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'l1' is not defined
>>> l2.append('obama')
>>> l2
['joe biden', 'donald trump', 'justin trudeau', 'barack obama', 'obama']
>>> 

l1 is deleted, so what is l2 pointing to? It seems l2 contains its own list now. Why does this happen?


Solution

  • del deletes variables, not objects. The variables l1 and l2 were "pointing" to (more correct term is "referencing") the same list, you deleted the variable l1, and you had the variable l2 left. An object is deleted only if the garbage collector detects that the object has no references left. A further del l2 should trigger that.

    If Python did allow you to delete an object, you could end up accidentally using still-alive variables or indices to access a deleted object, something like a dangling pointer.