Skip to content
Advertisement

Using a for loop to append to arrays in Numpy Python

The code below generates random integers within a given range within the for loop and I want to assign these values to the numpy arrays Values, up_value_one,up_value_two however the for loop below does not work. The Values of the Values, up_value_one,up_value_two are returned as empty arrays. How would I be able to use appender as the variable to append a,b,c to Values, up_value_one,up_value_two and update the arrays?

JavaScript

Expected Output:

JavaScript

Advertisement

Answer

You’re declaring a new appender in every iteration of the inside for loop, and because np.append doesn’t append in-place, nothing gets saved. I suggest you use list.append and then convert to np.array afterwards.

If you use list.append, your code requires minimal change. Simply change Values, up_value_one and up_value_two to lists and use list.append. Since it appends in-place, all these lists get updated in the loop:

JavaScript

But if you insist on using np.append, below is one way of doing it:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement