Problem with assigning variables of type List

Peter Hansen peter at engcorp.com
Wed Aug 21 19:29:08 EDT 2002


Abhishek Roy wrote:
> 
> 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]?

I think it's probably pretty simple.  Remember that in Python, all
names are just things that are bound to objects.  When you set
the second item (numbered 1) in the sequence "a" to be "a", you
are just storing a reference to the "a" object inside the object
itself.  Pretty much like having an array of pointers in C, and 
storing the address of the array as one of the array elements...

When you make the comparison, it takes the left value which is 
the reference to "a", and the right value, which it retrieves 
from the second position in the sequence, and compares them.
Since the right value is just a reference to "a" again, they
compare equal.  Effectively like comparing the pointers mentioned
above, where they would also be equal.

int * array[10] = { 1, 2, 3 };
array[1] = array

if (array[1] == array) 
   printf("equal\n");

-Peter



More information about the Python-list mailing list