pythonnumpynumpy-indexing

Numpy Slicing - Strange behavior


I have a problem with Numpy. Basically I just want to do a simple assignment in a for loop. But strangely this does not work. Here is my example code:

import numpy as np
test = np.zeros((1280,),dtype=int)
idx = 0
for i in range(32):
       test[idx:idx+40] = np.ones((40,),int)*1
       idx = idx + 1
print(np.where(test==0))

I would assume that after the loop all values in test are equal to 1, however the output of my program is (array([ 71, 72, 73, ..., 1277, 1278, 1279]),) I can't understand why there are still values of 0 in the array. Especially for example at index 72, which is in the middle of the second iteration of the loop.

Could you please help me? Thanks!


Solution

  • The maximal value of idx will be 31 when you use it for indexing, so before you increment it. From the array index 31 you will set 40 elements to 1. The last such element is at index 31+39, which is 70. The element at index 71 is then still 0.