{"record":{"id":"4b5e82b2052b894c","repo":"pandas-dev/pandas","slug":"categorical-input-must-be-list-like","errorCode":null,"errorMessage":"Categorical input must be list-like","messagePattern":"Categorical input must be list-like","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/categorical.py","lineNumber":412,"sourceCode":"\n    def __init__(\n        self,\n        values,\n        categories=None,\n        ordered=None,\n        dtype: Dtype | None = None,\n        copy: bool = True,\n    ) -> None:\n        dtype = CategoricalDtype._from_values_or_dtype(\n            values, categories, ordered, dtype\n        )\n        # At this point, dtype is always a CategoricalDtype, but\n        # we may have dtype.categories be None, and we need to\n        # infer categories in a factorization step further below\n\n        if not is_list_like(values):\n            # GH#38433\n            raise TypeError(\"Categorical input must be list-like\")\n\n        # null_mask indicates missing values we want to exclude from inference.\n        # This means: only missing values in list-likes (not arrays/ndframes).\n        null_mask = np.array(False)\n\n        # sanitize input\n        vdtype = getattr(values, \"dtype\", None)\n        if isinstance(vdtype, CategoricalDtype):\n            if dtype.categories is None:\n                dtype = CategoricalDtype(values.categories, dtype.ordered)\n        elif isinstance(values, range):\n            from pandas.core.indexes.range import RangeIndex\n\n            values = RangeIndex(values)\n        elif not isinstance(values, (ABCIndex, ABCSeries, ExtensionArray)):\n            values = com.convert_to_list_like(values)\n            if isinstance(values, list) and len(values) == 0:\n                # By convention, empty lists result in object dtype:","sourceCodeStart":394,"sourceCodeEnd":430,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/categorical.py#L394-L430","documentation":"Raised in the Categorical constructor when `values` is not list-like (is_list_like returns False). Categoricals wrap a finite enumeration of values, so a single scalar like an int or str cannot form one; pandas requires an iterable of values.","triggerScenarios":"`pd.Categorical(5)`, `pd.Categorical('a')`, or passing any non-iterable object as the first argument. Also when a user accidentally passes a single value where a sequence was intended.","commonSituations":"Programmatically building a Categorical from a variable that is sometimes a scalar; refactoring code that previously received a list down to a single element without wrapping.","solutions":["Wrap the scalar in a list: `pd.Categorical([value])`.","Ensure the input is a list/ndarray/Series/Index before passing; guard with `isinstance(values, (list, tuple, np.ndarray, pd.Series))`.","If the value comes from a DataFrame, pass the column (`df['col']`) rather than `df['col'].iloc[0]`."],"exampleFix":"# before\npd.Categorical('a')\n# after\npd.Categorical(['a'])","handlingStrategy":"type-guard","validationCode":"from pandas.api.types import is_list_like\n\ndef to_categorical(values, **kw):\n    if not is_list_like(values):\n        values = [values]\n    import pandas as pd\n    return pd.Categorical(values, **kw)","typeGuard":"def is_list_like_for_categorical(x) -> bool:\n    from pandas.api.types import is_list_like\n    return is_list_like(x)","tryCatchPattern":"try:\n    cat = pd.Categorical(value)\nexcept TypeError as e:\n    if 'must be list-like' in str(e):\n        cat = pd.Categorical([value])\n    else:\n        raise","preventionTips":["Always pass a sequence (list/tuple/ndarray/Series/Index) to Categorical.","Validate inputs with is_list_like before construction in dynamic code.","When selecting a single value, wrap in [ ] or pass the whole column."],"tags":["categorical","constructor","scalar-input","typeerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}