Redefining variables

question

#1

I am somewhat confused about the behavior when redefining variables, in particular why a second variable defined by a first variable changes when the first variable is redefined. Where can I read more about redefining variables and expected behavior?

x = rand(10)
y = x
x == y  # Expecting true

for ii=1:10
	x[ii] = rand()
end
x == y  # Expecting false but get true

x = rand(10)
x == y  # Expecting false

#2

No, it’s not a second variable defined by the first variable. Variables never have their own identity, only objects do. What you have is a second variable that’s bound to the same object that was bound to the first object at the time of assignment.
You also never redefine (i.e. rebind) the first variable in the loop, you mutated the object bound to it so the same object that’s bound to the second variable is also mutated.

x = rand(10) does redefine (rebind) the variable so the two variables are not bound to the same object anymore after that.

As I’ve said in other threads, in general, extra assignment should always be a no-op.


#3

I like this blog post on the topic http://www.johnmyleswhite.com/notebook/2014/09/06/values-vs-bindings-the-map-is-not-the-territory/


#4

Thank you, that is very helpful.