This is my first question, so if I'm being a total dweeb posting this, let me know why and how I can avoid it in the future!
I have a bit of python code that should just take a list, and multiply the jth component by -1. This is the code in question.
def flip(spins,j):
z = spins
z[j] = z[j]*-1
return z
However, what I am noticing is that if I try to do something like
spin = [1,1,1]
test = flip(spin,1)
it will assign the proper value [1,-1,1] to 'test', but it will also change the value of 'spin' to [1,-1,1]. I know there must be something totally obvious I'm overlooking, but I've been staring at this for 2 hours and still can't see it.
Thanks for your help!
Inside your function, z
and spins
refer to the same list, which is also known by the global name of spin
. If you modify one, those changes are visible through the other names as well. The variable z
is superfluous.
If you want z
to be a copy of spins
then just do:
z = spins[:]
or:
z = list(spins)
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