Search code examples
pythonarraysif-statementnested-loopsiterable

Python nested loops with if statements unexpected result


I am trying to figure out why this code performs differently from how I would expect. The code is:

for i1 in [xrange(567)]:
    W = x1[i1]
    Z = y[i1]
    ZW = np.array([z * (1/w) for z, w in zip(Z,W)])
    for j1 in [xrange(567)]:
        if j1 != i1:
            E1 = np.array([z - zw * w for z, zw, w in zip(Z,ZW,W)])

Where x1 is a (566,1)-array and y a (566,2)-array from a .csv file. Now I think that the statement if j1 != i1: doesn't work as it would be expected since if I try the more simple pattern:

for i in [range(567)]:
    for j in [range(567)]:
        if i != j:
            print i
            print j

It returns none


Solution

  • Your code needs to be modified:

    for i in range(567):
        for j in range(567):
            # do something here.
    

    As the commenters mentioned, omit the square brackets from your for loop line.