Search code examples
pythonloopstemporary

temp array overwriting original array in loop


I have a temporary array so that the original array won't be overwritten in each loop. I know that's not what it is actually doing, but I have no other explanation...

e = .95
f = .95
g = .95
h = .95

for a in range(0,10):
    e = e + .01
    for b in range(0,10):
        f = f + .01
        for c in range(0,10):
            g = g + .01
            for d in range(0,10):
                h = h + .01
                adj = []
                temp2 = original
                for x in temp2:
                    print x
                    x[0] = x[0] * e
                    x[4] = x[4] * e
                    x[1] = x[1] * f
                    x[5] = x[5] * f
                    x[2] = x[2] * g
                    x[6] = x[6] * g
                    x[3] = x[3] * h
                    x[7] = x[7] * h
                    x[8] = x[8] * e
                    x[12] = x[12] * e
                    x[9] = x[9] * f
                    x[13] = x[13] * f
                    x[10] = x[10] * g
                    x[14] = x[14] * g
                    x[11] = x[11] * h
                    x[15] = x[15] * h
                    adj.append(sum(x))

When I print x, it is increasing as if it is not a temporary variable.


Solution

  • temp2 is not a separate array, it is a reference to the same array. You probably want to copy x into temp2. One way to do this would be with the following line of code:

    import copy
    temp2 = copy.deepcopy(original)
    

    This assumes that this is the issue you're seeing. From your description and your code, it's not quite clear exactly what is not behaving as expected.