0

Say, for example, that I set x = [1,2,3], and then set temp = x.

Then, because x and temp are referring to the same value, if we do temp.reverse(), both temp and x are reversed.

Why, then, if we set x = [1,2,3] and set temp = x , and then temp = [7,8,9], is x not still equal to temp (x = [1,2,3] and temp = [7,8,9])? We've still modified temp, but unlike in the above example, the alias does not stick. Why is this?

alexqwx
  • 147
  • 1
  • 7
  • 1
    No you did not modified the **object** `tmp` refers to, you modified the **reference** of `tmp`... – Willem Van Onsem Mar 16 '17 at 15:29
  • The object behind the variable `temp` is not modified by assignment to `temp`. The statement "`temp = some_new_value`" (re)binds the name `temp` to a new object, leaving the old object, if any, intact. – Leon Mar 16 '17 at 15:31
  • 1
    Changing by mutating (.reverse()) is different than changing by rebinding (x = ...). See [Facts and Myths about Python Names and Values](https://nedbatchelder.com/text/names1.html) for more details. – Ned Batchelder Mar 16 '17 at 15:43
  • @NedBatchelder I think I understand that. But why, when you're creating a clone, does changing the thing of which you made a clone, not affect the clone itself? For example, if `a = [1,2,3]` and `b = a[:]`, and then we set `a.append(4)`, why is it that `b = [1,2,3]`? Surely, since `b` refers to `a[:]` which refers to `a`, changing `a` changes `a[:]` which changes `b`. Why is this not the case? – alexqwx Mar 16 '17 at 20:58
  • `a[:]` does not refer to a. It used a to create an entirely new list that has no relationship to a. Just like `2+2` is 4, and has no connection to 2 any more. – Ned Batchelder Mar 16 '17 at 23:47

0 Answers0