TheAlgorithms/Python · error · ValueError
index out of range
Error message
index out of range
What it means
Raised by index_2d_array_in_1d() in data_structures/arrays/index_2d_array_in_1d.py when the flat index is negative or >= rows * cols. The function validates the linear index against the total element count before computing array[index // cols][index % cols], so this fires only when the array itself is non-empty.
Source
Thrown at data_structures/arrays/index_2d_array_in_1d.py:97
...
ValueError: index out of range
>>> index_2d_array_in_1d([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], 12)
Traceback (most recent call last):
...
ValueError: index out of range
>>> index_2d_array_in_1d([[]], 0)
Traceback (most recent call last):
...
ValueError: no items in array
"""
rows = len(array)
cols = len(array[0])
if rows == 0 or cols == 0:
raise ValueError("no items in array")
if index < 0 or index >= rows * cols:
raise ValueError("index out of range")
return array[index // cols][index % cols]
if __name__ == "__main__":
import doctest
doctest.testmod()
View on GitHub (pinned to f5988cc097)
Solutions
- Clamp/validate before calling: 0 <= index < len(array) * len(array[0]).
- Check loop bounds: use range(rows * cols), not +1; remember indexes are 0-based.
- If the 2D list is ragged (rows of different lengths), normalize it first — the cols = len(array[0]) math assumes rectangular data.
Example fix
# before
for i in range(rows * cols + 1):
val = index_2d_array_in_1d(grid, i) # last i is out of range
# after
for i in range(rows * cols):
val = index_2d_array_in_1d(grid, i) Defensive patterns
Strategy: validation
Validate before calling
rows, cols = len(array), len(array[0])
if not 0 <= index < rows * cols:
raise IndexError(f'{index} outside 0..{rows*cols-1}')
val = index_2d_array_in_1d(array, index) Prevention
- Use range(rows * cols) in loops — indexes are 0-based
- Normalize ragged 2D lists before flat indexing
When it happens
Trigger: Calling index_2d_array_in_1d([[1,2],[3,4]], -1) or index_2d_array_in_1d([[1,2],[3,4]], 4) (max valid is 3). Also triggered by non-integer-like indexes after failed implicit coercion assumptions.
Common situations: Off-by-one loops (range(rows*cols + 1)), flat indexes computed from ragged/irregular 2D lists where len(array[0])*rows overestimates or underestimates actual counts, or passing a 1-based index to a 0-based API.
Related errors
- The parameter idx_original_string must be lower than len(bwt
- Invalid value of 'position'
- list index out of range
- The parameter idx_original_string must not be lower than 0.
- Both input arrays are empty.
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/e88bc64ce280cfbf.
Report an issue: GitHub.