pola-rs/polars · error · ValueError

negative slice lengths

Error message

negative slice lengths ({length!r}) are invalid for LazyFrame

What it means

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.

Solutions

  1. Use non-negative lengths: lf.slice(offset, n) with n >= 0
  2. 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)
  3. Use lf.tail(k) instead of negative-length slicing for the last rows

Example fix

// before
lf.slice(0, -5)  # last rows minus 5?
// after
lf.tail(5)  # or lf.slice(offset, n) with n >= 0
Defensive patterns

Strategy: validation

Validate before calling

def safe_slice(lf, offset, length):
    if length is not None and length < 0:
        raise ValueError('LazyFrame.slice requires length >= 0; use tail() for end rows')
    return lf.slice(offset, length)

Type guard

def slice_len_ok(length) -> bool:
    return length is None or length >= 0

Try / catch

try:
    out = lf.slice(offset, length)
except ValueError as e:
    if 'negative slice lengths' in str(e):
        out = lf.tail(-length)
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Understand the failure class

Background: "value must be between 0 and 1" / "out of range" / "must not be negative" errors: fixing range-validation failures across open-source libraries — this error's family across 42 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/4addb90d0de5a889. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/lazyframe/frame.py:6969

        ...         "a": ["x", "y", "z"],
        ...         "b": [1, 3, 5],
        ...         "c": [2, 4, 6],
        ...     }
        ... )
        >>> lf.slice(1, 2).collect()
        shape: (2, 3)
        ┌─────┬─────┬─────┐
        │ a   ┆ b   ┆ c   │
        │ --- ┆ --- ┆ --- │
        │ str ┆ i64 ┆ i64 │
        ╞═════╪═════╪═════╡
        │ y   ┆ 3   ┆ 4   │
        │ z   ┆ 5   ┆ 6   │
        └─────┴─────┴─────┘
        """
        if length and length < 0:
            msg = f"negative slice lengths ({length!r}) are invalid for LazyFrame"
            raise ValueError(msg)
        return self._from_pyldf(self._ldf.slice(offset, length))

    def limit(self, n: int = 5) -> LazyFrame:
        """
        Get the first `n` rows.

        Alias for :func:`LazyFrame.head`.

        .. engine-support:: in-memory, streaming, distributed

        Parameters
        ----------
        n
            Number of rows to return.

        Examples
        --------
        >>> lf = pl.LazyFrame(

View on GitHub (pinned to fe841f959e)