donnemartin/interactive-coding-challenges · error · IndexError

Invalid index

Error message

Invalid index

What it means

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.

Source

Thrown at bit_manipulation/bit/bit_solution.ipynb:189

  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def validate_index(func):\n",
    "    def validate_index_wrapper(self, *args, **kwargs):\n",
    "        for arg in args:\n",
    "            if arg < 0:\n",
    "                raise IndexError('Invalid index')\n",
    "        return func(self, *args, **kwargs)\n",
    "    return validate_index_wrapper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Bit(object):\n",
    "\n",
    "    def __init__(self, number):\n",
    "        if number is None:\n",
    "            raise TypeError('number cannot be None')\n",
    "        self.number = number\n",
    "\n",
    "    @validate_index\n",

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Check the index is >= 0 before calling get_bit/set_bit/clear_bit/update_bit
  2. Fix the loop or arithmetic producing the negative index
  3. Wrap calls in try/except IndexError if the index comes from untrusted input

Example fix

# before
bit.get_bit(index - 1)  # index=0 -> -1 raises

# after
pos = max(index - 1, 0)
bit.get_bit(pos)
Defensive patterns

Strategy: validation

Validate before calling

if index < 0:
    raise ValueError(f'index must be non-negative, got {index}')
bit.get_bit(index)

Type guard

def is_valid_bit_index(idx) -> bool:
    return isinstance(idx, int) and not isinstance(idx, bool) and idx >= 0

Try / catch

try:
    bit.get_bit(index)
except IndexError:
    logger.warning('negative bit index rejected: %r', index)

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28). Data as JSON: /api/errors/03ca2fb050ccbae5. Report an issue: GitHub.