I just thought I'd jot this down now that I've seen it - it would be nice to get a confirmation on this behavior; I did see How do I pass a variable by reference?, but I'm not sure how to interpret it in this context.
Let's say we have these two arrays/lists:
a = [1, 2, 3, 4]
b = [-1, a, -100, a[2], -1]
The interpreter initially sees them as:
>>> print(a)
[1, 2, 3, 4]
>>> print(b)
[-1, [1, 2, 3, 4], -100, 3, -1]
Now let's change a[2]
, and see what happens:
>>> print(a)
[1, 2, 55, 4]
>>> print(b)
[-1, [1, 2, 55, 4], -100, 3, -1]
So, wherever list b
has a reference to the list a
, the value has been updated - but wherever b
was initialized with (a reference to?) an element from list a
, it seems that Python expanded the value at initialization time, and thus stored the element by value (not by reference), so it's value obviously doesn't update.
Basically, I found a use case, where it would be convenient to be able to define e.g. b = [-1 a[2] -1]
, and then update a[2]
, and be able to count that the latest value of a[2]
will be emitted when getting the value of (in this case) b[1]
. Is there a way to do that in Python, without having to do b = [-1 a -1]
, and then reading b[1][2]
(I'd like to get the value of a[2]
just by using b[1]
)?