{"record":{"id":"b8394ffd9d69e073","repo":"pola-rs/polars","slug":"length-must-be-an-integer-string-or-expression","errorCode":null,"errorMessage":"'length' must be an integer, string, or expression, not {type(length).__name__}","messagePattern":"'length' must be an integer, string, or expression, not (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/expr/list.py","lineNumber":1134,"sourceCode":"        ┌─────────────┬───────────┐\n        │ a           ┆ slice     │\n        │ ---         ┆ ---       │\n        │ list[i64]   ┆ list[i64] │\n        ╞═════════════╪═══════════╡\n        │ [1, 2, … 4] ┆ [2, 3]    │\n        │ [10, 2, 1]  ┆ [2, 1]    │\n        └─────────────┴───────────┘\n        \"\"\"\n        if isinstance(offset, Collection) and not isinstance(offset, str):\n            msg = f\"'offset' must be an integer, string, or expression, not {type(offset).__name__}\"\n            raise TypeError(msg)\n        if (\n            length is not None\n            and isinstance(length, Collection)\n            and not isinstance(length, str)\n        ):\n            msg = f\"'length' must be an integer, string, or expression, not {type(length).__name__}\"\n            raise TypeError(msg)\n\n        offset_pyexpr = parse_into_expression(offset)\n        length_pyexpr = parse_into_expression(length)\n        return wrap_expr(self._pyexpr.list_slice(offset_pyexpr, length_pyexpr))\n\n    def head(self, n: int | str | Expr = 5) -> Expr:\n        \"\"\"\n        Slice the first `n` values of every sub-list.\n\n        .. engine-support:: in-memory, streaming, distributed\n\n        Parameters\n        ----------\n        n\n            Number of values to return for each sublist.\n\n        Examples\n        --------","sourceCodeStart":1116,"sourceCodeEnd":1152,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/expr/list.py#L1116-L1152","documentation":"Expr.list.slice() validates its `length` argument: when supplied it must be an integer, string column name, or Expr. Passing a Collection (list/tuple/dict/set) raises this TypeError. Polars checks the types client-side so invalid expressions fail fast.","triggerScenarios":"Calling Expr.list.slice(offset, length) with length as a collection, e.g. list.slice(0, [3]) or list.slice(1, (2,)).","commonSituations":"Passing a one-element list holding the intended length; confusing slice length with an end index; wrapping the length in a list during programmatic argument construction.","solutions":["Unwrap the collection and pass the integer directly: list.slice(0, 3).","If the value is in a list like [n], use n (i.e. values[0]).","If length should be dynamic, pass a column name (str) or an Expr such as pl.col('n')."],"exampleFix":"// before\npl.col('items').list.slice(0, [3])\n// after\npl.col('items').list.slice(0, 3)","handlingStrategy":"type-guard","validationCode":"if length is not None and not isinstance(length, (int, str, pl.Expr)):\n    raise TypeError(f'length must be int/str/Expr, got {type(length).__name__}')","typeGuard":"def is_valid_length(v) -> bool:\n    return v is None or isinstance(v, (int, str, pl.Expr))","tryCatchPattern":"try:\n    expr = pl.col('a').list.slice(offset, length)\nexcept TypeError:\n    expr = pl.col('a').list.slice(offset, int(length[0]))","preventionTips":["Unwrap one-element lists before passing as scalar arguments.","Keep the (offset, length) signature in mind; it is not Python slice(start, stop).","Type-annotate wrapper functions so linters catch list-typed scalars."],"tags":["python","polars","type-error","arguments"],"backgroundTag":"invalid-argument-value","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"}