To clarify how Python handles two equal objects

Weatherby,Gerard gweatherby at uchc.edu
Tue Jan 10 16:03:23 EST 2023


For clarification, equality is not identity in Python. e.g.

x = 7
y = 7.0
print(x == y)
print(x is y)

Will return
True
False

Full explanation at https://docs.python.org/3/reference/expressions.html#comparisons


From: Python-list <python-list-bounces+gweatherby=uchc.edu at python.org> on behalf of Chris Angelico <rosuav at gmail.com>
Date: Tuesday, January 10, 2023 at 3:47 PM
To: Python List <python-list at python.org>
Subject: Re: To clarify how Python handles two equal objects
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

On Wed, 11 Jan 2023 at 07:41, Jen Kris <jenkris at tutanota.com> wrote:
>
>
> Thanks for your comments.  I'd like to make one small point.  You say:
>
> "Assignment in Python is a matter of object references. It's not
> "conform them as long as they remain equal". You'll have to think in
> terms of object references the entire way."
>
> But where they have been set to the same object, an operation on one will affect the other as long as they are equal (in Python).  So I will have to conform them in those cases because Python will reflect any math operation in both the array and the matrix.
>

It's not that "an operation on one will affect the other" - it's that,
no matter how you refer to that object, you're affecting *that one
single object*. It's like when you're washing a window; the inside and
outside of the window are the exact same window, so regardless of
where you're looking at it from, it's the same single window and
changes affect it equally.

So you shouldn't have to replicate any changes. What should be
happening is that you find the right object to mutate, and mutate
that. For example:

stuff = [[1, 2, 3], [4, 5, 6]]
stuff.append(stuff[0])
print(stuff)

You now have two references to the same list, inside another list. Any
change to stuff[0] is a change to stuff[2], because they're the exact
same list. When you append "a reference to this list over here" (which
you found by asking for stuff[0]) to the outer list, you get that
list.

That's Python's object model, and trying to cheat it by copying
changes is just going to cause untold nightmares of desynchronization.

ChrisA
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iORRBJFui8Kn7WzY0ZRPfSdGKcmnDV81UffITsv7ExEAbBXEtv86qC3BOvGaDXCAY708Q4QbDXh0_wo7$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iORRBJFui8Kn7WzY0ZRPfSdGKcmnDV81UffITsv7ExEAbBXEtv86qC3BOvGaDXCAY708Q4QbDXh0_wo7$>


More information about the Python-list mailing list