{"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":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/lazyframe/frame.py","lineNumber":6969,"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":6951,"sourceCodeEnd":6987,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/lazyframe/frame.py#L6951-L6987","documentation":"LazyFrame.slice() does not support negative lengths (counting from the end like Python slicing) because lazy plans are executed without knowing the row count up front. A negative `length` raises this ValueError immediately.","triggerScenarios":"Calling lf.slice(offset, -5) or lf[-5:], or any dynamic computation yielding a negative length; passing length=0 is allowed (falsy check skips validation) but negative values raise.","commonSituations":"Translating pandas df.tail() or df[:-5] idioms directly to LazyFrame; computing length as a difference that can go negative; generic slicing helpers shared between DataFrame and LazyFrame.","solutions":["Use non-negative lengths: lf.slice(offset, n) with n >= 0","To drop the last k rows, use lf.slice(0, lf.count().collect().item() - k) or filter with a row index: lf.with_row_index().filter(pl.col('index') < total - k)","Use lf.tail(k) instead of negative-length slicing for the last rows"],"exampleFix":"// before\nlf.slice(0, -5)  # last rows minus 5?\n// after\nlf.tail(5)  # or lf.slice(offset, n) with n >= 0","handlingStrategy":"validation","validationCode":"def safe_slice(lf, offset, length):\n    if length is not None and length < 0:\n        raise ValueError('LazyFrame.slice requires length >= 0; use tail() for end rows')\n    return lf.slice(offset, length)","typeGuard":"def slice_len_ok(length) -> bool:\n    return length is None or length >= 0","tryCatchPattern":"try:\n    out = lf.slice(offset, length)\nexcept ValueError as e:\n    if 'negative slice lengths' in str(e):\n        out = lf.tail(-length)\n    else:\n        raise","preventionTips":["Never port pandas negative-slice idioms directly to LazyFrame","Use tail()/head()/limit() for end-of-frame access","Clamp computed lengths with max(0, n)"],"tags":["polars","python","lazyframe","slicing"],"backgroundTag":"value-out-of-range","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"}