5

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 :)

nextdoordoc
  • 1,727
  • 6
  • 20
  • 30
  • 1
    I can't reproduce your last example. – BrenBarn Jun 26 '13 at 01:55
  • i'm using 2.7.5 version now. well it works on my program. – nextdoordoc Jun 26 '13 at 02:06
  • 1
    Still can't reproduce your updated question. `from sys import getrefcount as r;g=[0];r(g);g.insert(0,g);r(g)` → 2, 3; Anyway, try checking the refcount *before* and *after* the insert. Maybe what you don't understand isn't what you think you don't understand. – kojiro Jun 26 '13 at 02:24
  • I think i should have thought deeply next time when questioning. Thanks really a lot~ :) – nextdoordoc Jun 26 '13 at 07:54

1 Answers1

4

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.
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358