Reference counts

Variables stay alive as long as the reference count is greater than 0. Let's look at a simple example:

In [1]: a = 12345

In [2]: b = a

In [3]: id(a)
Out[3]: 94821494630600

In [4]: id(b)
Out[4]: 94821494630600

In [5]: del a

In [6]: b
Out[6]: 12345

In [7]: id(a)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-dd34ca262c24> in <module>()
----> 1 id(a)

NameError: name 'a' is not defined

Line 3 and 4 show us that the objects memory address 94821494630600 is referred to by 'a' and 'b'. The object stays alive after 'a' is deleted because 'b' is still referring to it.

In the next example we create a list, create an additional reference to the first list element, delete the list and show that the first list element remained alive:

#!/usr/bin/env python
"""
file name: referenceCounts.py

this script demonstrates how a list element survives a
delete operation because it has an additional reference
"""

class cl():
    def __init__( self, name):
        self.name = name

def main():

    lst = []
    #
    # create a list of objects
    #
    for i in range( 1, 4): 
        o = cl( "name_%-d" % i)
        print( "creating %s, id %d" % (o.name, id( o)))
        lst.append( o) 
    #
    # the first list element is referenced by elm0
    #
    elm0 = lst[0]
    #
    # delete the list
    #
    while len( lst) > 0:
        elm = lst.pop()
        print( "deleting %s, id %d" % (elm.name, id( elm)))
        del elm
    #
    # ... and the first list element which has an additional reference is still alive
    #
    print( "Notice that the first list element is still alive %s id %d" % 
           (elm0.name, id( elm0)))

    return

if __name__ == "__main__":
    main()

The output:

$ python referenceCount.py 
creating name_1, id 139961137055864
creating name_2, id 139961137055936
creating name_3, id 139961137056008
deleting name_3, id 139961137056008
deleting name_2, id 139961137055936
deleting name_1, id 139961137055864
Notice that the first list element is still alive name_1 id 139961137055864