Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, what is the reference count of cyclic reference and why?

Here is a example of a cyclic reference of Python.

>>> a = [1]
>>> b = [2]
>>> a.append(b)
>>> b.append(a)

after this,

>>> sys.getrefcount(a) = 3
>>> sys.getrefcount(b) = 3

Why do a and b have a reference count of 3??

Sorry guys i just took a mistake.

the real question is the different one.

>>> GNU = ['is not Unix']
>>> GNU.insert(0, GNU)
>>> sys.getrefcount(GNU) = 4

Why is the reference count of 'GNU' is 4 ?

Thanks in advance :)

like image 400
nextdoordoc Avatar asked Oct 03 '22 17:10

nextdoordoc


1 Answers

There are 3 references to each:

  1. In the other's list in the first element.
  2. As an argument to sys.getrefcount().
  3. The current scope, i.e. bound to a and b.
like image 69
Ignacio Vazquez-Abrams Avatar answered Oct 23 '22 09:10

Ignacio Vazquez-Abrams