Problem with assigning variables of type List

Abhishek Roy abhishek at ocf.berkeley.edu
Thu Aug 22 22:56:11 CEST 2002


Peter Hansen <peter at engcorp.com> wrote in message news:<3D642244.D2B97B77 at engcorp.com>...
> 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.
By this reasoning Python's just checking id(a)==id(a[1]). But that won't
work here,
>>> b,c=[],[]
>>> b.append(c)
>>> c.append(b)
>>> b==c
1
>>> id(b[0]),id(c[0])
(135319372, 135319340)

Even more peculiarly,
>>> x=[1,2,3]
>>> x[1]=x
>>> x.append(x)
>>> x[1]==x[3]
causes Python (2.1.3) to hang.

Abhishek



More information about the Python-list mailing list