{"record":{"id":"fec7d1b40b32266e","repo":"pola-rs/polars","slug":"category-index-out-of-range-key","errorCode":null,"errorMessage":"category index out of range: {key}","messagePattern":"category index out of range: (.+?)","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/datatypes/classes.py","lineNumber":851,"sourceCode":"        elif phys == \"u32\":\n            return pldt.UInt32\n        else:\n            msg = \"unknown physical dtype\"\n            raise RuntimeError(msg)\n\n    def is_global(self) -> bool:\n        \"\"\"Returns whether this refers to the global categories.\"\"\"\n        return self._categories.is_global()\n\n    def __getitem__(self, key: str | int) -> str | int:\n        if isinstance(key, str):\n            if (cat := self._categories.get_cat(key)) is None:\n                raise KeyError(key)\n            return cat\n        elif isinstance(key, int):\n            if (s := self._categories.cat_to_str(key)) is None:\n                msg = f\"category index out of range: {key}\"\n                raise IndexError(msg)\n            return s\n        else:\n            msg = f\"invalid key type {type(key)}; expected str or int\"\n            raise TypeError(msg)\n\n    def __contains__(self, item: str | int) -> bool:\n        if isinstance(item, str):\n            return self._categories.get_cat(item) is not None\n        elif isinstance(item, int):\n            return self._categories.cat_to_str(item) is not None\n        else:\n            return False\n\n    def __iter__(self) -> Iterator[str | None]:\n        for i in range(self._categories.num_cats_upper_bound()):\n            yield self._categories.cat_to_str(i)\n\n    def to_series(self) -> Series:","sourceCodeStart":833,"sourceCodeEnd":869,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/datatypes/classes.py#L833-L869","documentation":"Indexing a Categories object with an integer converts the category index back to its string name. If the integer is not a valid category index (negative or >= number of categories), an IndexError with 'category index out of range: {key}' is raised.","triggerScenarios":"categories[42] where the categories collection has fewer than 43 entries; stale indices saved before the category mapping changed; indexing with codes from a different column/dataset.","commonSituations":"Persisting physical codes to disk and remapping later after categories changed; off-by-one loops over range(len)+1; sharing indices across datasets with different category sets.","solutions":["Validate 0 <= idx < len(categories) before indexing","Wrap in try/except IndexError","Recompute the index from the current column's categories instead of reusing stored codes"],"exampleFix":"// before\nname = categories[idx]  # idx=42\n// after\nname = categories[idx] if 0 <= idx < len(categories) else None","handlingStrategy":"validation","validationCode":"if not (0 <= idx < len(categories)):\n    raise ValueError(f'index {idx} outside 0..{len(categories)-1}')\nname = categories[idx]","typeGuard":"def valid_index(categories, idx: int) -> bool:\n    return isinstance(idx, int) and 0 <= idx < len(categories)","tryCatchPattern":"try:\n    name = categories[idx]\nexcept IndexError:\n    name = None","preventionTips":["Always bounds-check indices against len(categories)","Do not persist physical codes across schema changes without remapping","Avoid off-by-one loops (range(n), not range(n+1))"],"tags":["polars","categorical","indexerror","bounds"],"backgroundTag":"index-out-of-range","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}