2

While I was creating a basic for-loop in Python within a function in order to work with a dynamic variable length (z) I've just come across the following error:

Rs = []
z = []
N = 120
m = 1
for i in range(1, N):
    Rs[i] = z[m]
    m = m + 1
Rs[i] = z[m]  
IndexError: list index out of range

For the sake of clarity, I will explain better what I'm trying to do. I would like to solve an equation system which is composed by a dynamical number of unknowns. I've started to use the "static" method and It works perfectly. Basically, the code is more or less as follows:

from scipy.optimize import fsolve

def fixEqSyst(z):
    v1 = z[0]
    v2 = z[1]
    v3 = z[2]
    v4 = z[3]
    f=np.zeros(4)
    f[0] = 2*v1-3*v2+7*v3**2
    f[1] = v1+3*v2**2-9*v3
    f[2] = -3v1**2+12*v2+7*v3
    f[3] = 4*v1+5*V2*v3
    return f

z = fsolve(fixEqSyst, [0, 0, 0, 0])

Basing on the fact that now I will face with a dynamic number of unknowns and functions, is there any alternative solution than of what I've already put in place? (with a for-loop strategy)

MarianD
  • 13,096
  • 12
  • 42
  • 54
Ty87
  • 21
  • 4
  • 2
    `z` has length equal to 0, you can verify that by calling `len(z)` within the loop and thus, since you 're trying to access an element in an empty list, you get `IndexError`. You need to assign some element to `z` before the loop. But what is it that you're trying to do? – Vasilis G. Dec 15 '18 at 16:01

2 Answers2

2

Just in the first iteration of your loop you get

Rs[1] = z[1]

but z[1] don't exists, because z = [].

(The same for Rs[1].)

I haven't any idea how to fix it because I'm unable to guess what you wanted perform with you code.

Maybe you wanted to copy the contain of your - supposed nonempty - list z to Rs. Then they are 2 different simple solutions:

Rs = z   

Attention! This is not a copy operation, this only associates other name to the same object, so every change in z will produce the same change in Rs and vice versa.

Rs = z[:]

This is the true (but shallow) copy. For simple lists this is the same as a deep copy.

MarianD
  • 13,096
  • 12
  • 42
  • 54
1

When you assign a value to an array in python, the element must already exist. When you are assigning Rs[i] = z[m], you are assigning values out of the range of the list. You can use the += operator on a list in order to make it large enough, like this:

Rs = []
z = []
N = 120
m = 1
for i in range(m+N):
    z += [m+i]
for i in range(N):
    Rs += [z[m]]
    m = m + 1

Note that += can only concatenate a list to another list. So this will work:

mylist = [1, 2, 3]
mylist += [4]

But this will not:

mylist = [1, 2, 3]
mylist += 4

Here is more on the += operator on lists.

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42