{"record":{"id":"03ca2fb050ccbae5","repo":"donnemartin/interactive-coding-challenges","slug":"invalid-index","errorCode":null,"errorMessage":"Invalid index","messagePattern":"Invalid index","errorType":"validation","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"bit_manipulation/bit/bit_solution.ipynb","lineNumber":189,"sourceCode":"  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Code\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def validate_index(func):\\n\",\n    \"    def validate_index_wrapper(self, *args, **kwargs):\\n\",\n    \"        for arg in args:\\n\",\n    \"            if arg < 0:\\n\",\n    \"                raise IndexError('Invalid index')\\n\",\n    \"        return func(self, *args, **kwargs)\\n\",\n    \"    return validate_index_wrapper\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"class Bit(object):\\n\",\n    \"\\n\",\n    \"    def __init__(self, number):\\n\",\n    \"        if number is None:\\n\",\n    \"            raise TypeError('number cannot be None')\\n\",\n    \"        self.number = number\\n\",\n    \"\\n\",\n    \"    @validate_index\\n\",","sourceCodeStart":171,"sourceCodeEnd":207,"githubUrl":"https://github.com/donnemartin/interactive-coding-challenges/blob/358f2cc60426d5c4c3d7d580910eec9a7b393fa9/bit_manipulation/bit/bit_solution.ipynb#L171-L207","documentation":"Raised by the validate_index decorator in the Bit class when any positional argument (the bit index) passed to a decorated method is negative. It is an IndexError used to guard bit operations like get_bit, set_bit, clear_bit, and update_bit from invalid positions.","triggerScenarios":"Calling bit.get_bit(-1), bit.set_bit(-3), bit.clear_bit(-1), or bit.update_bit(-2, 1) on a Bit instance — any decorated method receiving a negative index argument.","commonSituations":"Looping over bit positions with an off-by-one error, computing an index from user input or subtraction that goes negative, or porting code that assumed unsigned wraparound behavior.","solutions":["Check the index is >= 0 before calling get_bit/set_bit/clear_bit/update_bit","Fix the loop or arithmetic producing the negative index","Wrap calls in try/except IndexError if the index comes from untrusted input"],"exampleFix":"# before\nbit.get_bit(index - 1)  # index=0 -> -1 raises\n\n# after\npos = max(index - 1, 0)\nbit.get_bit(pos)","handlingStrategy":"validation","validationCode":"if index < 0:\n    raise ValueError(f'index must be non-negative, got {index}')\nbit.get_bit(index)","typeGuard":"def is_valid_bit_index(idx) -> bool:\n    return isinstance(idx, int) and not isinstance(idx, bool) and idx >= 0","tryCatchPattern":"try:\n    bit.get_bit(index)\nexcept IndexError:\n    logger.warning('negative bit index rejected: %r', index)","preventionTips":["Clamp computed indexes with max(0, ...) when appropriate","Assert loop bounds before bit-manipulation loops","Treat negative results from subtraction as a bug, not an input"],"tags":["python","bit-manipulation","index-error","argument-validation"],"backgroundTag":"negative-index-validation","analyzedSha":"358f2cc60426d5c4c3d7d580910eec9a7b393fa9","analyzedAt":"2026-08-28T10:16:54.480Z","schemaVersion":2},"datasetVersion":"2026-08-28T11:17:15.048Z"}