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()
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.


I like this blog post on the topic


Thank you, that is very helpful.