Problem with assigning variables of type List

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Aug 22 11:26:01 CEST 2002


Peter Hansen <peter at engcorp.com> wrote in 
news:3D642244.D2B97B77 at engcorp.com:

>> 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.
> 

How does this fit with your explanation?

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

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list