Reference counting in python

Viewed 38

I am learning how reference counting works in python and I am confused.

def get_full_list ():
    a = object ()
    b = object ()
    c = object ()
    l = [a, b, c]
    return l

l = get_full_list ()
print (sys.getrefcount (l)) #-> prints 2 (getrefcount and l)
print (sys.getrefcount (l[0])) #-> prints 2 (getrefcount and l[0])

I hope I am right with this one.

But with code like this

def get_full_list ():
    a = object ()
    b = object ()
    c = object ()
    l = [a, b, c]
    return l

def print_ref_count (l):
    print (sys.getrefcount (l)) #-> 4 (getrefcount, param l, l and ??????) It can't be that l when calling print_ref_count function right ?
    print (sys.getrefcount (l[0]))# -> 2 (getrefcount and l[0])

l = get_full_list ()
print_ref_count (l)

Why I am getting 4 ref count there ? From where is that fourth reference ?
Thanks for explaining.

0 Answers
Related