Write Python. Understand every error.

Open the editor

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.

Try this code in Py-CRAFT

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

Learn the ideas behind it

Other common errors

Share this page: