Tuple index out of range

I’m having a problem trying to run my code, so I’ve tried to test the part that isn’t working. And it happens that when I use integers it works, but I need the array with float numbers and in this case it’s not working, I’m getting the error “tuple index out of range”. Both matrices are 1x81. Could someone please tell me how can I fix this?

n = 9
c = 4
U_aux = []

U = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
     0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
     0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 
     1]


for i in range(n): 
    for j in range(n):
        k = i*n + j

        if (i%c == 0) and (j%c == 0):
            U_aux.append(U[k])
print(U_aux, '\n')

U = [-8.41470985e-01, -6.81638760e-01, -4.79425539e-01, -2.47403959e-01,
  3.33066907e-16,  2.47403959e-01,  4.79425539e-01,  6.81638760e-01,
  8.41470985e-01, -8.33843761e-01, -8.00032668e-01, -6.08192095e-01,
 -3.25207319e-01,  9.80459808e-15,  3.25207319e-01, 6.08192095e-01,
  8.00032668e-01,  8.33843761e-01, -5.81147313e-01, -5.76435639e-01,
 -4.47982795e-01, -2.41978646e-01,  1.36309486e-14,  2.41978646e-01,
  4.47982795e-01,  5.76435639e-01,  5.81147313e-01, -1.19943972e-01,
 -1.16307504e-01, -8.53355534e-02,-4.34878176e-02,  9.57975558e-15,
  4.34878176e-02,  8.53355534e-02,  1.16307504e-01,  1.19943972e-01,
  3.78965423e-01,  3.89177337e-01,  3.19770624e-01, 1.80542815e-01,
  7.10981512e-18, -1.80542815e-01, -3.19770624e-01,-3.89177337e-01,
 -3.78965423e-01,  7.15338958e-01,  7.31044969e-01,  5.94841259e-01,
  3.33049195e-01, -9.32965702e-15, -3.33049195e-01, -5.94841259e-01,
 -7.31044969e-01, -7.15338958e-01,  7.52048363e-01,  7.67919215e-01,
  6.23724461e-01,  3.48656958e-01, -1.30101869e-14, -3.48656958e-01,
 -6.23724461e-01, -7.67919215e-01, -7.52048363e-01,  4.74997926e-01,
  4.84909559e-01,  3.93652622e-01 , 2.19943579e-01, -9.08171401e-15,
 -2.19943579e-01, -3.93652622e-01, -4.84909559e-01, -4.74997926e-01,
 -8.88178420e-16,  4.44089210e-15, -2.55351296e-15,  3.33066907e-15,
 -8.60422844e-16,  1.88737914e-15, -8.88178420e-16, -2.22044605e-16,
  1.99840144e-15],


for i in range(n): 
    for j in range(n):
        k = i*n + j

        if (i%c == 0) and (j%c == 0):
            U_aux.append(U[k])
print(U_aux, '\n')

Look at the line where you assign to U. Is the right-hand side a list? No, it’s a tuple of length 1 because of the trailing comma after the ].

1 Like

The trailing comma after the ] means that U will be a tuple with one element, where that element is the list of 81 float values. After fixing this, the code works as expected (except, of course, that it’s appending elements to U_aux which still contains the elements from the first loop).