Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Polars · Function

pl.fold

Builds an expression that performs a left fold across multiple columns or expressions horizontally, applying a callback from an initial accumulator. It supports custom row-wise reductions and optional output-type control.

How it works

pl.fold starts with an accumulator expression and repeatedly applies a two-argument function to that accumulator and each value from the selected expressions. It returns an expression, so it can be used inside selections and other expression contexts; the accumulator also guides output-type inference unless an explicit type is supplied.

Syntax

polars.fold(acc: IntoExpr, function: Callable[[Series, Series], Series], exprs: Sequence[Expr | str] | Expr, *, returns_scalar: bool = False, return_dtype: DataTypeExpr | PolarsDataType | None = None) → Expr

Parameters

NameTypeDescription
accIntoExprAccumulator expression initialized when the fold starts.
functionCallable[[Series, Series], Series]Function applied to the accumulator and each value; it returns the new accumulator.
exprsSequence[Expr | str] | ExprExpressions to aggregate; may also be a wildcard expression.
returns_scalarbool = FalseWhether the function's result is a scalar; this must be set correctly.
return_dtypeDataTypeExpr | PolarsDataType | None = NoneOutput datatype; if omitted, it is inferred from the accumulator.

Returns

Expr

Key points

  • The function reduces values horizontally across columns, processing them row by row with left-fold semantics.
  • function combines the current accumulator with each successive input value and returns the next accumulator.
  • exprs defines which expressions participate in the fold and can also be a wildcard expression.

Common mistakes

  • Set returns_scalar accurately when the callback produces a scalar; the documentation states that this option must be correct.
  • Without return_dtype, Polars infers the result type from the accumulator, which can affect the output type.

Example: Row-wise fold across columns

import polars as pl

_df = pl.DataFrame({"a": [1, 2, 3], "b": [3, 4, 5], "c": [5, 6, 7]})
result = _df.select(
    pl.fold(
        acc=pl.lit(1),
        function=lambda acc, value: acc + value,
        exprs=pl.col("*"),
    ).alias("total")
)
print(result)

Adds the accumulator to each selected column from left to right for every row.

When to use it

Custom arithmetic reductions

Compute a custom row-wise total or product over selected columns.

Boolean or predicate aggregation

Apply predicates across a wildcard-selected group of columns.

General-purpose horizontal folds

Use a callback when built-in horizontal aggregations do not express the required reduction.

Interview questions

QWhat does pl.fold do?

pl.fold performs a left fold across multiple expressions, starting from acc and repeatedly calling function(accumulator, value). It produces an expression that can be used in a query.

Follow-up: How would you make a row-wise product? Initialize acc with pl.lit(1) and use multiplication as the callback.

QHow are input columns selected?

exprs identifies the expressions whose values are processed, and it may be a sequence or a single expression such as a wildcard column selector. The callback receives the accumulated result and the next value.

Follow-up: How can you restrict the fold to two columns? Pass pl.col("a", "b") as exprs.

QHow is the result type determined?

return_dtype specifies the output datatype. If omitted, Polars infers the datatype from the accumulator expression, so choosing an appropriately typed accumulator is significant.

Follow-up: When should it be supplied explicitly? Use it when callback operations produce a type that should not be inferred from the accumulator.

  • polars.sum_horizontal
  • polars.mean_horizontal
  • polars.min_horizontal

Source: polars.fold — Polars documentation. Checked 2026-10-15.