Redefining variables

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

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 Likes

I like this blog post on the topic Values vs. Bindings: The Map is Not the Territory · John Myles White

1 Like

Thank you, that is very helpful.

1 Like