On Wed, 11 Jan 2023 at 07:14, Jen Kris via Python-list <python-list@python.org> wrote: > > I am writing a spot speedup in assembly language for a short but > computation-intensive Python loop, and I discovered something about Python > array handling that I would like to clarify. > > For a simplified example, I created a matrix mx1 and assigned the array arr1 > to the third row of the matrix: > > mx1 = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] > arr1 = mx1[2] > > The pointers to these are now the same: > > ida = id(mx1[2]) - 140260325306880 > idb = id(arr1) - 140260325306880 > > That’s great because when I encounter this in assembly or C, I can just > borrow the pointer to row 3 for the array arr1, on the assumption that they > will continue to point to the same object. Then when I do any math > operations in arr1 it will be reflected in both arrays because they are now > pointing to the same array: >
That's not an optimization; what you've done is set arr1 to be a reference to that object. > But on the next iteration we assign arr1 to something else: > > arr1 = [ 10, 11, 12 ] > idc = id(arr1) – 140260325308160 > idd = id(mx1[2]) – 140260325306880 > > Now arr1 is no longer equal to mx1[2], and any subsequent operations in arr1 > will not affect mx1. Yep, you have just set arr1 to be a completely different object. > So where I’m rewriting some Python code in a low level language, I can’t > assume that the two objects are equal because that equality will not remain > if either is reassigned. So if I do some operation on one array I have to > conform the two arrays for as long as they remain equal, I can’t just do it > in one operation because I can’t rely on the objects remaining equal. > > Is my understanding of this correct? Is there anything I’m missing? > 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. ChrisA -- https://mail.python.org/mailman/listinfo/python-list