Search code examples
pythongarbage-collectiondel

Python del and garbage collecting


First look at my Python code,

s = [[1, 2], [3, 6], [9, 6]]
t = s
i = s[0]

del i
del t[0]

There is three references for [2, 1]; t[0], s[0] and "i", so if we try and delete of them it shouldn't effect on [1,2] because [1,2] still has two another reference so Python garbage-collection system doesn't remove [1,2] do to the having no reference. So why deleting "i" doesn't effect on [1,2] but deleting t[0] does.


Solution

  • You mistakenly understand the function of the del statement. For variable names:

    del variable_name
    

    The del statement deletes the binding of the name to the object from the global variable.

    For the combination of container and key:

    del container[key]
    

    It is responsible for deleting the elements in the container according to the key.

    Use some simple symbols to explain what you are doing. Here I use a pair of parentheses to represent an object, and a word ref or a variable name represents a reference. After you create these objects, it will look like this:

     t s
     ↓ ↓
    (list [ref, ref])
     i ┌───┘    └───────┐
     ↓ ↓                ↓
    (list [ref, ref]) (list [ref, ref])
       ┌───┘  ┌─┘     ┌──────┘┌───┘
       ↓      ↓       ↓       ↓
    (int 1) (int 2) (int 3) (int 6)
    

    If you execute del i, the final result is as follows:

     t s
     ↓ ↓
    (list [ref, ref])
       ┌───┘    └───────┐
       ↓                ↓
    (list [ref, ref]) (list [ref, ref])
       ┌───┘  ┌─┘     ┌──────┘┌───┘
       ↓      ↓       ↓       ↓
    (int 1) (int 2) (int 3) (int 6)
    

    If you execute del t[0], the final result is as follows:

     t s
     ↓ ↓
    (list [ref])
     i     └────────────┐
     ↓                  ↓
    (list [ref, ref]) (list [ref, ref])
       ┌───┘  ┌─┘     ┌──────┘┌───┘
       ↓      ↓       ↓       ↓
    (int 1) (int 2) (int 3) (int 6)