To clarify how Python handles two equal objects

Chris Angelico rosuav at gmail.com
Tue Jan 10 15:45:18 EST 2023


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


More information about the Python-list mailing list