comparing lists and/or tuples 'by pointer'

Greg Copeland gtcopeland at EarthLink.Net
Fri Sep 24 12:33:44 EDT 1999


greg andruk wrote:
> 
> Philip Lijnzaad <lijnzaad at ebi.ac.uk> wrote:
> 
> > a=[1,2,3]
> > b=[1,2,3]
> > a==b is true (but not after a[0]=4).  While this deep comparison is useful,
> > it is also useful to have the cheaper option that says that a and b actually
> > refer to the same storage (in Lisp terms: eq vs. equal).  How to do this in
> > Python? Thanks for any info,
> 
> To see if two names point to the same object, you can use 'is':
> 
> >>> a = [1,2,3]
> >>> b = [1,2,3]
> >>> c = a
> >>> a is b
> 0
> >>> a is c
> 1

I think what he was wanting was a = b = [1,2,3]
whereby, he can now do his a[0] = 4.  Since a and b should now be the
same object, it should give him what he desires.  Let's see:

>>> a = b = [1,2,3]
>>> a==b
1
>>> a is b
1
>>> a[0]=4
>>> a
[4, 2, 3]
>>> b
[4, 2, 3]
>>> a==b
1
>>> a is b
1

Clearly you can see the difference between same objects and same values
here.  In the original poster's message, he was testing for value
equality of distint objects.  Now, we are using assignment and equality
of the same objects, having verified this with the usage of 'is'.

Greg





More information about the Python-list mailing list