To clarify how Python handles two equal objects

Jen Kris jenkris at tutanota.com
Wed Jan 11 10:33:50 EST 2023


Yes, I did understand that.  In your example, "a" and "b" are the same pointer, so an operation on one is an operation on the other (because they’re the same memory block).  My issue in Python came up because Python can dynamically change one or the other to a different object (memory block) so I have to be aware of that when handing this kind of situation. 


Jan 10, 2023, 17:31 by greg.ewing at canterbury.ac.nz:

> On 11/01/23 11:21 am, Jen Kris wrote:
>
>> where one object derives from another object (a = b[0], for example), any operation that would alter one will alter the other.
>>
>
> I think you're still confused. In C terms, after a = b[0], a and b[0]
> are pointers to the same block of memory. If you change that block of
> memory, then of course you will see the change through either pointer.
>
> Here's a rough C translation of some of your Python code:
>
> /* mx1 = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] */
> int **mx1 = (int **)malloc(3 * sizeof(int *));
> mx1[0] = (int *)malloc(3 * sizeof(int));
> mx1[0][0] = 1;
> mx1[0][1] = 2;
> mx1[0][2] = 3;
> mx1[1] = (int *)malloc(3 * sizeof(int));
> mx1[1][0] = 4;
> mx1[1][1] = 5;
> mx1[1][2] = 6;
> mx1[2] = (int *)malloc(3 * sizeof(int));
> mx1[2][0] = 7;
> mx1[2][1] = 8;
> mx1[2][2] = 9;
>
> /* arr1 = mx1[2] */
> int *arr1 = mx[2];
>
> /* arr1 = [ 10, 11, 12 ] */
> arr1 = (int *)malloc(3 * sizeof(int));
> arr1[0] = 10;
> arr1[1] = 11;
> arr1[2] = 12;
>
> Does that help your understanding?
>
> -- 
> Greg
> -- 
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list