Error guide · NumPy errors
IndexError: index 3 is out of bounds for axis 0 with size 3
You asked for a position that the array does not have.
Example
import numpy as np a = np.array([10, 20, 30]) print(a[3])
What Python says
IndexError: index 3 is out of bounds for axis 0 with size 3
As printed by Python 3.12. Other versions may word it slightly differently.
Why it happens
Positions start at 0, so an array of three elements has positions 0, 1 and 2. Position 3 is out of bounds. For a 2D array, each dimension has its own limit, and the message names the axis: axis 0 runs down the rows and axis 1 runs across the columns.
How to fix it
import numpy as np a = np.array([10, 20, 30]) print(a[2]) print(a[-1])
Output: 30 ⏎ 30
Tips
- The last position is
a.shape[axis] - 1, or simply-1. - For
m[row, column], checkm.shapeto see both limits. - Loops should stop before
len(a), never at it.