When I tried to change the variable assigned to it, it was also changed.
You're not changing variables there. del y[-1]
does nothing to the variable y
, it does something to the object (list) denoted by y
. (As opposed to del y
, which really does delete the variable y
.)
Why does this happen?
Because y
is an (only) element of x
. The fact that you append it to x
doesn't change y
in any way. It is still the same object.
I would appreciate any help finding a way around this.
It depends on what do you want behavior to be. If you want "value semantics", that is, for y
to be copied when appending it to x
, just say so:
x.append(y.copy())