3

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?

kubajed
  • 31
  • 1
  • Does this answer your question? [If two variables point to the same object, why doesn't reassigning one variable affect the other?](https://stackoverflow.com/questions/56667280/if-two-variables-point-to-the-same-object-why-doesnt-reassigning-one-variable) – MisterMiyagi Jun 03 '20 at 10:45

2 Answers2

4
 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]
Aziz
  • 20,065
  • 8
  • 63
  • 69
0

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.

Dejene T.
  • 973
  • 8
  • 14
  • 1
    This is not what's being asked. They assign `a = b` later in the code and expect `c` to change. – bereal Jun 03 '20 at 10:47