๐Ÿ€Zerve chosen as NCAA's Agentic Data Platform for 2026 Hackathonยท๐ŸงฎMeet the Zerve Team at Data Decoded Londonยท๐Ÿ“ˆWe're hiring โ€” awesome new roles just gone live!
Back
Numpy

IndexError: Index Out of Bounds - How to Fix It

Answer

This error means you're trying to access an array element at a position that doesn't exist. Fix it by checking the array's shape with .shape before indexing. Remember that NumPy uses zero-based indexing, so an array of length 5 has valid indices 0 through 4.

Why This Happens

NumPy arrays have fixed dimensions. If your array has 10 elements and you try to access index 10, it fails because valid indices are 0-9. This commonly happens with off-by-one errors, hardcoded indices that don't match the actual data size, or after operations that change array dimensions.

Solution

The rule: always check .shape or len() before indexing. Use negative indices for accessing elements from the end, and use slicing when you want to avoid errors on out-of-bounds access.

import numpy as np

arr = np.array([10, 20, 30, 40, 50])

# โŒ Problematic: index 5 doesn't exist in a 5-element array
arr[5]
# IndexError: index 5 is out of bounds for axis 0 with size 5

# โœ… Fixed: check shape first
print(arr.shape)  # (5,)
print(len(arr))   # 5
arr[4]  # last valid index

# โœ… Fixed: use negative indexing for last elements
arr[-1]  # last element (50)
arr[-2]  # second to last (40)

# โœ… Fixed: use bounds checking before access
idx = 5
if idx < len(arr):
    value = arr[idx]
else:
    value = None  # or handle the error

# โœ… For 2D arrays, check both dimensions
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d.shape)  # (2, 3)
arr_2d[1, 2]  # valid: row 1, column 2
# arr_2d[2, 0]  # invalid: only 2 rows (0 and 1)

# โœ… Safe slicing (never raises IndexError)
arr[10:20]  # returns empty array if out of bounds

Better Workflow

In Zerve, array shapes are always visible in block outputs. No need for print statements to debug. When an IndexError appears, check the upstream block to see the actual shape, create a new block to test safe indexing approaches, and verify the fix instantly. Zerve's variable inspector shows shape and type metadata automatically, so you always know what you're working with before you index into it.

Better workflow

Related Topics

Decision-grade data work

Explore, analyze and deploy your first project in minutes