Semantics of ==
David M. Cooke
cookedm+news at physics.mcmaster.ca
Tue Mar 16 20:47:37 EST 2004
At some point, axelboldt at yahoo.com (Axel Boldt) wrote:
> Still trying to understand "=="... It appears as if two equal objects
> can become unequal if you perform the same operations on them:
>
> >>> l=[1]
> >>> s=l
> >>> l.append(s)
You're building a cyclic list: l contains a reference to itself.
General advice: don't do that unless you know what you're doing.
> >>> w=[1]
> >>> r=[1,w]
> >>> w.append(r)
> >>> s
> [1, [...]]
> >>> w
> [1, [1, [...]]]
> >>> s==w
> True
>
> Note that they're equal, yet are printed differently.
Element-by-element, they're equal, yes.
> >>> s[0]=2
> >>> w[0]=2
> >>> s==w
> False
>
> All of a sudden they have become unequal.
That's b/c s originally looked like this if we expand out the
recursion a few more levels:
[1, [1, [1, [1, [...]]]]]
where each sub-list is also s.
w also looks like
[1, [1, [1, [1, [...]]]]]
where the *second* sub-list is w.
Set the first elements to 2:
s is now:
[2, [2, [2, [2, ...]]]]
w is now:
[2, [1, [2, [1, ...]]]]
See? The second sub-list of w is not w, so it wasn't changed.
--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
More information about the Python-list
mailing list