0

I am newbie in Python and maybe my problem is very simple.

I have created a list of 250 zeros called x, x = np.zeros(250), and I have a loop where I perform some calculations, at each iteration I produce two x's for example in the first iteration the x[0] and x[1] and so on in a list called temp_x. i.e., the first temp_x has the x[0] and x[1]

I want to save the output at the end of each iteration to the corresponding positions of the x. For example at the end of the first iteration temp_x has two values I want to assign them to the first positions of x.

What I am doing wrong?

x[i, i+1] = x_temp
Er1Hall
  • 147
  • 2
  • 11

3 Answers3

1

This should work just fine x[i] = x[i+1] = x_temp

IAmVisco
  • 373
  • 5
  • 14
  • ValueError: setting an array element with a sequence. – Er1Hall Mar 20 '19 at 13:04
  • Apparently numpy creates not a list but a `numpy.ndarray` object with `np.zeros()` call, I haven't worked with it much but it still worked for me in REPL – IAmVisco Mar 20 '19 at 13:17
1

As mentioned in @IAmVisco's answer, chained assignment will work.

However, to go into the reason your code doesn't:

When you type something like x[i, i+1], Python understands the value in the square brackets as a tuple, and therefore actually attempts to execute x[(i, i + 1)], which accesses the element at row i and column i + 1. Since there is no such element (x is a 1D array), it fails with the error "too many indices for array".

If you actually want to access two (or more) elements in that way, your indices should be in a form of a np.ndarray (a list would work too):

>>> x = np.ones(10)
>>> x[np.array([0, 1])] = 2
>>> x
array([2., 2., 1., 1., 1., 1., 1., 1., 1., 1.])
gmds
  • 19,325
  • 4
  • 32
  • 58
0

I'm not sure IAmVisco's answer will do what is required, it will instead set both of the elements of x to the list x_temp.

What I think you need instead is:

x[i], x[i+1] = x_temp

This unpacks each element of x_temp into each element of x

japester
  • 56
  • 2