pola-rs/polars · error · ValueError

the length of `{value_name}` ({len(values)}) does not match

Error message

the length of `{value_name}` ({len(values)}) does not match the length of `{match_name}` ({n_match})

What it means

ValueError from extend_bool (py-polars/src/polars/_utils/various.py:550-564). Sort/top-k style APIs accept per-column boolean flags either as a single bool (broadcast to all columns) or as a sequence with exactly one entry per key column. extend_bool broadcasts the scalar or validates the sequence length against len(by)/len(exprs) and names both sides in the message, e.g. the length of `descending` (3) does not match the length of `by` (2).

Source

Thrown at py-polars/src/polars/_utils/various.py:563

        del stack_frame

    return objects


def extend_bool(
    value: bool | Sequence[bool],  # noqa: FBT001
    n_match: int,
    value_name: str,
    match_name: str,
) -> Sequence[bool]:
    """Ensure the given bool or sequence of bools is the correct length."""
    values = [value] * n_match if isinstance(value, bool) else value
    if n_match != len(values):
        msg = (
            f"the length of `{value_name}` ({len(values)}) "
            f"does not match the length of `{match_name}` ({n_match})"
        )
        raise ValueError(msg)
    return values


def in_terminal_that_supports_colour() -> bool:
    """
    Determine (within reason) if we are in an interactive terminal that supports color.

    Note: this is not exhaustive, but it covers a lot (most?) of the common cases.
    """
    if hasattr(sys.stdout, "isatty"):
        # can enhance as necessary, but this is a reasonable start
        return (
            sys.stdout.isatty()
            and (
                sys.platform != "win32"
                or "ANSICON" in os.environ
                or "WT_SESSION" in os.environ
                or os.environ.get("TERM_PROGRAM") == "vscode"

View on GitHub (pinned to df599052da)

Solutions

  1. Pass a scalar to apply to all columns: descending=True
  2. Make the list length equal len(by): one bool per sort/expr key
  3. Derive flags from the key list: descending=[cfg[c] for c in by_cols]

Example fix

# before
lf.sort_by(['a', 'b'], descending=[True, False, True])  # ValueError

# after
lf.sort_by(['a', 'b'], descending=[True, False])
Defensive patterns

Strategy: validation

Validate before calling

def norm_flags(by: list, flags: bool | list[bool]) -> list[bool]:
    if isinstance(flags, bool):
        return [flags] * len(by)
    if len(flags) != len(by):
        raise ValueError(f'need {len(by)} flags, got {len(flags)}')
    return list(flags)

Prevention

When it happens

Trigger: LazyFrame/Expr.sort_by(by=['a','b'], descending=[True, False, True]); pl.top_k_by style calls in polars/functions/lazy.py with descending/nulls_last lists longer or shorter than exprs; Series/DataFrame methods that route through require_same_type callers of extend_bool with 'reverse' vs 'by' (Expr.sort_by(reverse=...)).

Common situations: Adding a sort key and forgetting to extend the descending/nulls_last lists; building the flags list from a different source than the column list (stale config dict); passing a single-element list while sorting by multiple columns.

Related errors


AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16). Data as JSON: /api/errors/f2da204314bf393f. Report an issue: GitHub.