krahets/hello-algo · error · IndexError

インデックスが範囲外です

Error message

インデックスが範囲外です

What it means

MyList.get raises IndexError('インデックスが範囲外です', 'index out of range') when index is negative or >= self._size, before indexing into the backing array self._arr. It is the explicit bounds check of this hand-rolled dynamic array, enforcing that reads stay within the logical element count rather than the larger allocated capacity. The message is in Japanese because the file is the ja/ localized variant of the textbook code.

Source

Thrown at ja/codes/python/chapter_array_and_linkedlist/my_list.py:30

        """コンストラクタ"""
        self._capacity: int = 10  # リスト容量
        self._arr: list[int] = [0] * self._capacity  # 配列(リスト要素を格納)
        self._size: int = 0  # リストの長さ(現在の要素数)
        self._extend_ratio: int = 2  # リスト拡張時の増加倍率

    def size(self) -> int:
        """リストの長さを取得(現在の要素数)"""
        return self._size

    def capacity(self) -> int:
        """リスト容量を取得する"""
        return self._capacity

    def get(self, index: int) -> int:
        """要素にアクセス"""
        # インデックスが範囲外なら例外を送出する。以下同様
        if index < 0 or index >= self._size:
            raise IndexError("インデックスが範囲外です")
        return self._arr[index]

    def set(self, num: int, index: int):
        """要素を更新"""
        if index < 0 or index >= self._size:
            raise IndexError("インデックスが範囲外です")
        self._arr[index] = num

    def add(self, num: int):
        """末尾に要素を追加"""
        # 要素数が容量を超えると、拡張機構が発動する
        if self.size() == self.capacity():
            self.extend_capacity()
        self._arr[self._size] = num
        self._size += 1

    def insert(self, num: int, index: int):
        """中間に要素を挿入"""

View on GitHub (pinned to 69932aed18)

Solutions

  1. Validate against live size: `if 0 <= index < lst.size(): lst.get(index)`.
  2. Prefer the provided size() accessor over cached counts when computing indices.
  3. Recompute indices after any mutation that changes size.
  4. In try/except, catch IndexError and surface a localized/domain message to the user.

Example fix

// before
val = lst.get(maybe_stale_index)
// after
if 0 <= maybe_stale_index < lst.size():
    val = lst.get(maybe_stale_index)
else:
    val = None
Defensive patterns

Strategy: validation

Validate before calling

if 0 <= index < lst.size():
    val = lst.get(index)

Type guard

def valid_list_index(l, index) -> bool:
    return 0 <= index < l.size()

Try / catch

try:
    val = lst.get(index)
except IndexError:
    val = None

Prevention

When it happens

Trigger: Calling get(index) with index >= size after elements were removed; negative index; using a cached index from before a remove() shrank _size; off-by-one loops such as range(0, size()+1).

Common situations: Index drift after remove(); confusion between size (logical count) and capacity (allocated slots); 0-based vs 1-based numbering mistakes; loops that overshoot the upper bound by one.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/12ad67bcb66cc256. Report an issue: GitHub.