{"record":{"id":"4c190cedad45644f","repo":"TheAlgorithms/Python","slug":"index-out-of-range-4c190c","errorCode":null,"errorMessage":"index out of range","messagePattern":"index out of range","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"linear_algebra/src/lib.py","lineNumber":143,"sourceCode":"            return sum(prods)\n        else:  # error case\n            raise Exception(\"invalid operand!\")\n\n    def copy(self) -> Vector:\n        \"\"\"\n        copies this vector and returns it.\n        \"\"\"\n        return Vector(self.__components)\n\n    def component(self, i: int) -> float:\n        \"\"\"\n        input: index (0-indexed)\n        output: the i-th component of the vector.\n        \"\"\"\n        if isinstance(i, int) and -len(self.__components) <= i < len(self.__components):\n            return self.__components[i]\n        else:\n            raise Exception(\"index out of range\")\n\n    def change_component(self, pos: int, value: float) -> None:\n        \"\"\"\n        input: an index (pos) and a value\n        changes the specified component (pos) with the\n        'value'\n        \"\"\"\n        # precondition\n        assert -len(self.__components) <= pos < len(self.__components)\n        self.__components[pos] = value\n\n    def euclidean_length(self) -> float:\n        \"\"\"\n        returns the euclidean length of the vector\n\n        >>> Vector([2, 3, 4]).euclidean_length()\n        5.385164807134504\n        >>> Vector([1]).euclidean_length()","sourceCodeStart":125,"sourceCodeEnd":161,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/src/lib.py#L125-L161","documentation":"Raised by Vector.component(i) in linear_algebra/src/lib.py:143 when the requested index falls outside the valid range [-len, len). The method deliberately validates i is an int within that range and raises a bare Exception 'index out of range' rather than letting the list raise IndexError — but note it also rejects non-int indices (e.g. floats or bool-handled edge cases) with the same message.","triggerScenarios":"Calling v.component(5) on a 3-component vector, v.component(-4) (one past the negative end), or v.component(1.0) — a float index that would work with list indexing fails the isinstance(i, int) check.","commonSituations":"Off-by-one loop bounds (range(len(v) + 1)), index arithmetic that goes negative past the start, or indices computed from float math (i / 2) that were never coerced to int.","solutions":["Clamp and int-cast the index: i = int(i); if not -len(v) <= i < len(v): raise ...","Fix loop bounds to range(len(v)) — an inclusive end is the usual off-by-one.","Remember negative indices are supported down to -len, but -len - 1 and beyond raise.","Catch Exception narrowly if indices come from user input and you want graceful handling."],"exampleFix":"// before\nv = Vector([1, 2, 3])\nval = v.component(3)  # Exception: index out of range\n\n// after\ni = min(max(int(i), -len(v)), len(v) - 1)\nval = v.component(i)","handlingStrategy":"validation","validationCode":"i = int(i)\nn = len(v)\nif not -n <= i < n:\n    raise IndexError(f\"index {i} out of range for size {n}\")\nvalue = v.component(i)","typeGuard":"def is_valid_vector_index(v, i) -> bool:\n    return isinstance(i, int) and -len(v) <= i < len(v)","tryCatchPattern":"try:\n    value = v.component(i)\nexcept Exception as e:\n    if \"index out of range\" in str(e):\n        raise IndexError(f\"component({i!r}) invalid for size {len(v)}\") from e\n    raise","preventionTips":["Always int-cast indices computed from float math before calling component().","Loop with range(len(v)); an inclusive bound is the classic off-by-one trigger.","Note the accepted range is [-n, n) — negative indices work down to -len but the method also rejects non-int types with the same message.","Validate indices from user/file input before touching the vector."],"tags":["linear-algebra","vector","index-out-of-range","off-by-one","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}