Consider the following:
a=[0,1] #our starting value
a=[a,1] #=> [[0,1],1] as expected
I would anticipate the following to have the same result:
a=[0,1] #same starting place
a[0]=a #should make a the same thing as it was above, right?
a #=> [[...],1] !!!
In the first example, the second assignment refers to the value of a
before the assignment was made. In the second example, the second assignment performs a recursive assignment. This feels like different behavior to me. Is this behavior in fact consistent? If so can someone please explain why?
In the first example you are creating a new array with the value [[0,1], 1]. Then you are reassigning a
to refer to this array.
In the second example you are not creating a new array, nor are you changing what a
refers to. You are changing the existing array to contain a reference to itself. That's very different.
The first example is roughly equivalent to this code:
a = [0, 1] # Step 1
b = [a, 1] # Step 2
a = b # Step 3
In pictures it looks like this:
--- |a| --- | v [0, 1]
--- --- |a| |b| --- --- | | | v | [ref, 1] | | +------------+ v [0, 1]
a
to point to the array created in step 2:--- --- |a| |b| --- --- | | +----------+ v [ref, 1] | +-------------+ v [0, 1]
On the other hand, the code in the second example gives you this:
--- |a| --- | +---+ | v | [ref, 1] | | +-----+
Here there is still only one array, and a
still points to it. But now the first element in the array refers to the array itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With