{"record":{"id":"06995c22537ec8e8","repo":"pandas-dev/pandas","slug":"input-must-be-list-like","errorCode":null,"errorMessage":"Input must be list-like","messagePattern":"Input must be list-like","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/categorical.py","lineNumber":3217,"sourceCode":"    \"\"\"\n    Factorize an input `values` into `categories` and `codes`. Preserves\n    categorical dtype in `categories`.\n\n    Parameters\n    ----------\n    values : list-like\n\n    Returns\n    -------\n    codes : ndarray\n    categories : Index\n        If `values` has a categorical dtype, then `categories` is\n        a CategoricalIndex keeping the categories and order of `values`.\n    \"\"\"\n    from pandas import CategoricalIndex\n\n    if not is_list_like(values):\n        raise TypeError(\"Input must be list-like\")\n\n    categories: Index\n\n    vdtype = getattr(values, \"dtype\", None)\n    if isinstance(vdtype, CategoricalDtype):\n        values = extract_array(values)\n        # The Categorical we want to build has the same categories\n        # as values but its codes are by def [0, ..., len(n_categories) - 1]\n        cat_codes = np.arange(len(values.categories), dtype=values.codes.dtype)\n        cat = Categorical.from_codes(cat_codes, dtype=values.dtype, validate=False)\n\n        categories = CategoricalIndex(cat)\n        codes = values.codes\n    else:\n        # The value of ordered is irrelevant since we don't use cat as such,\n        # but only the resulting categories, the order of which is independent\n        # from ordered. Set ordered to False as default. See GH #15457\n        cat = Categorical(values, ordered=False)","sourceCodeStart":3199,"sourceCodeEnd":3235,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/categorical.py#L3199-L3235","documentation":"Raised by factorize_from_iterables (categorical.py:3217) when the input values is not list-like. factorize requires an iterable of values to assign integer codes; a scalar has nothing to enumerate. The is_list_like guard rejects scalars (int, str-as-scalar, None) before any encoding happens.","triggerScenarios":"pd.factorize(5), pd.factorize('a') (single string, not a list of strings). pd.Categorical.from_codes with a scalar codes argument. Internal calls from pd.cut/qcut when the input collapses to a scalar. Passing a single datetime instead of a DatetimeIndex.","commonSituations":"User passes a bare string expecting it to be treated as a one-element sequence. Variable that was expected to be a list is actually a single value from upstream logic. Calling factorize inside a loop where some iterations yield a scalar.","solutions":["Wrap the scalar in a list: pd.factorize([value]).","Ensure the variable feeding factorize is always iterable; coerce with np.asarray or pd.Index.","For strings intended as a sequence of characters, pass list(s) explicitly.","Add an isinstance(x, (list, tuple, np.ndarray, pd.Series)) guard upstream."],"exampleFix":"# before\npd.factorize('a')  # TypeError: Input must be list-like\n\n# after\npd.factorize(['a'])  # (array([0]), Index(['a'], dtype='object'))","handlingStrategy":"validation","validationCode":"import numpy as np\nif not isinstance(values, (list, tuple, np.ndarray, pd.Series, pd.Index)):\n    values = [values]\ncodes, uniques = pd.factorize(values)","typeGuard":"from collections.abc import Iterable\nimport pandas as pd\n\ndef ensure_listlike(x):\n    if isinstance(x, (str, bytes)):\n        return [x]\n    if isinstance(x, Iterable):\n        return list(x)\n    return [x]","tryCatchPattern":null,"preventionTips":["Wrap scalar inputs in a list before factorize.","Document factorize entry points as list-like only."],"tags":["categorical","factorize","argument-validation","list-like"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}