Take a simple code:
y = [1,2,3] def plusOne(y): for x in range(len(y)): y[x] += 1 return y print plusOne(y), y a = 2 def plusOne2(a): a += 1 return a print plusOne2(a), a
The y values ββchange, but the a value remains unchanged. I already learned that this is because it is volatile and the other is not. But how to change the code so that the function does not change the list?
For example, to do something like this (in pseudocode for simplicity):
a = [1,2,3,...,n] function doSomething(x): do stuff with x return x b = doSomething(a) if someOperation(a) > someOperation(b): do stuff
EDIT: Sorry, but I have another question about nested lists . See this code:
def change(y): yN = y[:] for i in range(len(yN)): if yN[i][0] == 1: yN[i][0] = 0 else: yN[i][0] = 1 return yN data1 = [[1],[1],[0],[0]] data2 = change(data1)
This does not work here. What for? Again: how to avoid this problem? I understand why it does not work: yN = y [:] copies the values ββof y to yN, but the values ββare also lists, so the operation must be doubled for each list in the list. How to perform this operation with nested lists?
source share