Problem with assigning variables of type List

Michael Hudson mwh at python.net
Thu Aug 22 05:06:42 EDT 2002


abhishek at ocf.berkeley.edu (Abhishek Roy) writes:

> Peter Hansen <peter at engcorp.com> wrote in message news:<3D631501.3A308807 at engcorp.com>...
> > Abhishek Roy wrote:
> > > Just a nagging doubt, using the terminology in the above guide what's going
> > > on with:
> > > >>> a=[1,2,3]
> > > >>> a[1]=a
> > > >>> a
> >  [1, [...], 3]
> > > >>> a==a[1]
> > > 1
> > 
> > You created a recursive object, which contains a reference to itself.
> > Since this goes down infinitely deep, and you can't compare infinities,
> > I thought, I wonder whether the "1" is mathematically true.  It is
> > certain true according to Python's rules though.
> I was just wondering how it's implemented. Since a[1]=a is really 
> a.__setitem__(1,a), what exactly happens when you call this function
> and then later make the comparison a==a[1]?

Well, ASCII art time:

>>> a = [1,2,3]

    ,---.     +-----+      +---+
    | a |---->| [0]-+----->| 1 |
    `---'     | [1]-+---.  +---+
              | [2]-+-. |  +---+
              +-----+ | `->| 2 |
                      |    +---+
                      |    +---+
                      `--->| 3 |
                           +---+

>>> a[1] = a

                 ,----.
                 |    |
                \/    |
    ,---.     +-----+ |
    | a |---->| [0]-+-'
    `---'     | [1]-+---.
              | [2]-+-. |  +---+
              +-----+ | `->| 2 |
                      |    +---+
                      |    +---+
                      `--->| 3 |
                           +---+

Then when you execute a[1] == a, roughly what happens is

the python interpreter notices we're comparing lists
 so it asks if the first two elements are equal
  the python interpreter notices we're comparing lists
   so it asks if the first two elements are equal
    the python interpreter notices we're comparing lists
     so it asks if the first two elements are equal
      the python interpreter notices we're comparing lists
       so it asks if the first two elements are equal
        the python interpreter notices we're comparing lists
         so it asks if the first two elements are equal
          ...

after this has happend a certain number of times (25?  something like
that) some clever code checks for a recursive data structure in a way
I don't really understand...

Cheers,
M.

-- 
                    >> REVIEW OF THE YEAR, 2000 <<
                   It was shit. Give us another one.
                           -- NTK Now, 2000-12-29, http://www.ntk.net/



More information about the Python-list mailing list