rohitg00/ai-engineering-from-scratch · error · IndexError
Expected indices, got
Error message
Expected {len(self._shape)} indices, got {len(indices)} What it means
Raised in Tensor._flat_index when the number of indices passed to __getitem__/__setitem__ does not equal the tensor's rank. Full indexing requires one integer per axis in this basic implementation; too few or too many indices cannot be resolved to a single flat offset.
Solutions
- Supply exactly rank indices, e.g. t[0, 1] for a 2-D tensor and t[0] for a 1-D one
- Check tensor.rank before indexing in generic code
- Add slicing/partial-index support if your use case needs sub-tensor views
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at phases/01-math-foundations/12-tensor-operations/code/tensors.py:74 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26).
Data as JSON: /api/errors/22f762b3d24d2a8b.
Report an issue: GitHub.
Appendix: source
Thrown at phases/01-math-foundations/12-tensor-operations/code/tensors.py:74
@property
def shape(self):
return self._shape
@property
def rank(self):
return len(self._shape)
@property
def size(self):
return len(self._data)
@property
def strides(self):
return self._strides
def _flat_index(self, indices):
if len(indices) != len(self._shape):
raise IndexError(
f"Expected {len(self._shape)} indices, got {len(indices)}"
)
idx = 0
for i, (ind, stride) in enumerate(zip(indices, self._strides)):
if ind < 0 or ind >= self._shape[i]:
raise IndexError(
f"Index {ind} out of range for axis {i} with size {self._shape[i]}"
)
idx += ind * stride
return idx
def __getitem__(self, indices):
if not isinstance(indices, tuple):
indices = (indices,)
if len(indices) == len(self._shape):
return self._data[self._flat_index(indices)]
raise IndexError("Partial indexing not supported in this basic implementation")
View on GitHub (pinned to 39ea8a1c6d)