{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/categorical.py#L394-L430","documentation":"Raised in `Categorical.__init__` when the `values` argument is not list-like (GH#38433). Categoricals represent a 1-D sequence of codes; a scalar or other non-iterable cannot back one, so the constructor refuses early before any dtype inference.","triggerScenarios":"Calling `pd.Categorical(5)`, `pd.Categorical('a')` (single string is technically scalar in this check context), or passing a single datetime/None.","commonSituations":"Programmatically constructing a Categorical from a function that unexpectedly returned a scalar instead of a sequence; off-by-one indexing that yielded a single cell; refactoring list-building code that sometimes yields a non-iterable.","solutions":["Wrap the scalar in a list: `pd.Categorical([value])`.","Validate upstream: ensure the source produces a sequence before passing it in.","Use `pd.Series(value, dtype='category')` if you want a single-element categorical Series.","If the value can legitimately be scalar or list, normalize: `values = [values] if not is_list_like(values) else values`."],"exampleFix":"# before\nimport pandas as pd\ncat = pd.Categorical('a')  # TypeError: Categorical input must be list-like\n\n# after\ncat = pd.Categorical(['a'])","handlingStrategy":"validation","validationCode":"from pandas.api.types import is_list_like\n\ndef to_categorical(values, **kwargs):\n    if not is_list_like(values):\n        values = [values]\n    return pd.Categorical(values, **kwargs)","typeGuard":"from pandas.api.types import is_list_like\n\ndef is_categorical_input(values) -> bool:\n    return is_list_like(values)","tryCatchPattern":null,"preventionTips":["Validate `is_list_like(values)` at the boundary of any function that builds a Categorical from dynamic input.","When indexing a single cell that must become a Categorical, wrap with `[...]`.","Use `pd.Series(value, dtype='category')` for single-element categorical Series."],"tags":["categorical","constructor","scalar-input","typeerror"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}