{"record":{"id":"4addb90d0de5a889","repo":"pola-rs/polars","slug":"negative-slice-lengths-length-r-are-invalid-fo","errorCode":null,"errorMessage":"negative slice lengths ({length!r}) are invalid for LazyFrame","messagePattern":"negative slice lengths \\((.+?)\\) are invalid for LazyFrame","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/lazyframe/frame.py","lineNumber":7208,"sourceCode":"        ...         \"a\": [\"x\", \"y\", \"z\"],\n        ...         \"b\": [1, 3, 5],\n        ...         \"c\": [2, 4, 6],\n        ...     }\n        ... )\n        >>> lf.slice(1, 2).collect()\n        shape: (2, 3)\n        ┌─────┬─────┬─────┐\n        │ a   ┆ b   ┆ c   │\n        │ --- ┆ --- ┆ --- │\n        │ str ┆ i64 ┆ i64 │\n        ╞═════╪═════╪═════╡\n        │ y   ┆ 3   ┆ 4   │\n        │ z   ┆ 5   ┆ 6   │\n        └─────┴─────┴─────┘\n        \"\"\"\n        if length and length < 0:\n            msg = f\"negative slice lengths ({length!r}) are invalid for LazyFrame\"\n            raise ValueError(msg)\n        return self._from_pyldf(self._ldf.slice(offset, length))\n\n    def limit(self, n: int = 5) -> LazyFrame:\n        \"\"\"\n        Get the first `n` rows.\n\n        Alias for :func:`LazyFrame.head`.\n\n        .. engine-support:: in-memory, streaming, distributed\n\n        Parameters\n        ----------\n        n\n            Number of rows to return.\n\n        Examples\n        --------\n        >>> lf = pl.LazyFrame(","sourceCodeStart":7190,"sourceCodeEnd":7226,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/lazyframe/frame.py#L7190-L7226","documentation":"LazyFrame.slice() (and head/limit which build on slicing) rejects negative lengths: unlike DataFrame, lazy frames cannot express 'all but the last N rows' cheaply because row count is unknown until execution. A negative length raises ValueError.","triggerScenarios":"lf.slice(0, -5); lf.head(-1); length computed as n - total where it goes negative for small frames; code ported from pandas/DataFrame where negative slicing is allowed.","commonSituations":"Pagination/windowing logic with computed lengths; take(N-k) style calculations on frames smaller than k; reusable code shared between DataFrame and LazyFrame.","solutions":["Clamp the length: length = max(0, length) before slicing","Use lf.collect() first if negative slicing semantics (drop last rows) are genuinely needed, then slice the DataFrame","Compute lengths from known row counts only after collecting","Use tail()/head() with non-negative counts"],"exampleFix":"# before\nlf2 = lf.slice(0, requested - reserved)  # may be negative\n\n# after\nlf2 = lf.slice(0, max(0, requested - reserved))","handlingStrategy":"validation","validationCode":"length = max(0, length) if length is not None else None\nlf2 = lf.slice(offset, length)","typeGuard":"def is_non_negative_length(length) -> bool:\n    return length is None or length >= 0","tryCatchPattern":null,"preventionTips":["Clamp computed lengths with max(0, n)","Collect first when negative (drop-from-end) semantics are required","Keep slicing logic shared between frame types only after normalizing lengths"],"tags":["polars","lazyframe","slice","negative-value"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}