Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function is changing the value of my input, and I can't figure out why

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!

like image 745
aetb Avatar asked Sep 22 '13 23:09

aetb


1 Answers

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)
like image 92
kindall Avatar answered Sep 20 '22 00:09

kindall