To clarify how Python handles two equal objects

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Jan 10 20:31:43 EST 2023


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


More information about the Python-list mailing list