0

I came across a piece of very confusing python code as follows:

V = 16*[0.1]

key = True
i = 0 

while key:
    delta = 0 
    V_origin = V
    for s in range(16):

        v = V[s]
        V[s] = V_origin[s] * 2
        delta = max(delta,abs(v - V[s]))

    if delta < 0.01:
        key = False 
    print(V, V_origin)

the logic behind this code is, I have two variables in while-for loop V and V_origin, where the value of V is changed in for loop. In this way, when print (V,V_origin) together, I figure they would differ on value because V_origin does not change in the for-loop. However, it turns out that they are the same in final printing of every loop in the macro while loop, which means that V_origin is changed in the middle. I wonder why? Am I missing something on the loop structure here?

exteral
  • 991
  • 2
  • 12
  • 33
  • This has nothing to do with loops. `V_origin = V` **are referring to the same object**. If that object changes, then both variables will reflect that change. Read this: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga May 12 '18 at 18:19
  • 1
    use V_origin = V[:] to create a copy of the array, if you use `V_origin = V` they will both refer to the same array. You can try it out with this little snippet `a = [1]; b = a; c = a[:]; a[0] = 2; print(b[0]==2, c[0]==2)` – ktzr May 12 '18 at 18:21
  • Thx guys, it really helps ! – exteral May 12 '18 at 18:26

0 Answers0