0

I have the following code:

def TEST():
vals = [[0]*len(K_values)]*len(u_values)
for p in range(len(u_values)):
    u = u_values[p]
    for i in range(len(K_values)):
        K = K_values[i]
        vals[p][i] = u * K
return vals

u_values and K_values are 11-element long 1-D arrays. vals is a 2-D array of zeros that (should have) has its [p][i] element updated with u * K upon every loop.

The problem is that instead of changing the index p upon each (outer) loop, python always uses p=0 - this means that upon every loop, only u_values[0] is ever used. At first I thought this was because the outer for loop was only executing once; however, when viewing the code output (vals), it is clear that the outer loop IS looping len(u_values) times; it's just always with p=0 (otherwise, I would expect that only the zeroth column of the vals array would be nonzero).

  • I suggest modify the code: l_u = len(u_values)... for p in range(l_u), and similar for the other loop. That will at least isolate the problem a bit better. – gwideman Aug 22 '16 at 22:52
  • doing `[[0]*x]*y` creates a list of references to the same sub-list, you need to use comprehension like `vals = [[0]*len(K_values) for _ in range(len(u_values))]` once you have that fixed you should consider using [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) to clean up those nasty loops: `for p,u in enumerate(u_values): for i,K in enumerate(K_values): ...` – Tadhg McDonald-Jensen Aug 22 '16 at 22:54
  • Thank you very much @TadhgMcDonald-Jensen - your suggestion of using `vals = [[0]*len(K_values) for _ in range(len(u_values))]` works perfectly – CrossProduct Aug 22 '16 at 23:59

0 Answers0