Python aliasing

352 Views Asked by At

I understand that given this code

a = [1,2,3]
b = [4,5,6]
c = a

and then by doing this

a[0] = 0

I wil change first positions of both a and c. Could somebody explain why this doesn't apply when I do this:

a = b

ie. why c doesn't become equal to b?

2

There are 2 best solutions below

1
Dejene T. On

Because python interprets the line of code from the beginning of the code to the bottom line. Therefore, you have been assigned the b to a, after assigning a to c. The value of c is not changed until reassigning c.

0
Aziz On
 a = [1,2,3]
 b = [4,5,6]

 #       a  ────────>    [1,2,3]
 #       b  ────────>    [4,5,6]


 c = a    # Changing 'c' to point at the list that 'a' points at

 #       c  ─────┐
 #       a  ─────┴──>    [1,2,3]
 #       b  ────────>    [4,5,6]


 a = b    # Changing 'a' to point at the list that 'b' points at

 #       c  ─────┐
 #       a  ──┐  └──>    [1,2,3]
 #       b  ──┴─────>    [4,5,6]