Search code examples
pythonindexingindex-error

IndexError: index X is out of bounds for axis 0 with size Y (Python)


I'm quite new with Python so I might just be overseeing something:

After creating a random 8x8 numpy.ndarray I'm attempting to change all 0 values to 1 with a "for" loop.

Following code doesn't work:

rng = np.random.default_rng()
y=rng.integers(10,size=(8,8))
for i in range (0,len(np.where(y==0)[0])):
    y[np.where(y==0)[0][i],np.where(y==0)[1][i]] = 1

I get the "IndexError: index X is out of bounds for axis 0 with size Y " error, where X and Y keep on changing because of the randomness of the y-array.

However, if I add some variables instead of writing the whole code at once, it works. The code looks like this:

rng = np.random.default_rng()
y=rng.integers(10,size=(8,8))
index_x,index_y=np.where(y==0)
for i in range(0,len(index_x)):
    y[index_x [i],index_y[i]] = 1

Could someone please explain to me why the 1st code doesn't work, although both codes are basically the same?

Thanks in advance and happy new year!


Solution

  • Don't use a for loop for this, try this:

    rng = np.random.default_rng()
    y=rng.integers(10,size=(8,8))
    
    y[y==0] = 1