# Fold functions¶

Fold functions [0] reduce an iterable to a single value.

## Builtins¶

There are several instances of fold functions Python library:

and also several fold operators:

• the boolean and and or operator.
• the mathematical operators +, -, *, /, //, % and **.
• the bitwise operators <<, >>, |, ^ and &.
• the comparison operators <, <=, ==, !=, >=, >.

## Builtin Library functions¶

functools.reduce() is probably the most general function that could be used to recreate all the builtin functions. For example:

• reduce(lambda x, y: x and y, iterable) is equivalent to all()
• reduce(lambda x, y: x or y, iterable) is equivalent to any()
• reduce(lambda x, y: x + y, iterable) is equivalent to sum()
• reduce(lambda x, y: x if x < y else y, iterable) is equivalent to min()
• reduce(lambda x, y: x if x > y else y, iterable) is equivalent to max()
• reduce(lambda x, y: x + 1, iterable, 0) is equivalent to len()

Warning

These functools.reduce() functions are much slower than the builtins!

There are several other fold functions in the standard library and in third-party packages, most notably:

The iteration_utilities package includes some additional fold functions:

## Helper functions¶

Included in the iteration_utilities package are several helper functions that are based on normal Python code but chosen to evaluate faster than alternatives:

## Fold to other data structure¶

Most fold functions reduce an iterable by discarding most of the iterable. However iteration_utilities includes functions that discard no elements or only a few:

This list contains some builtin Python functions for completeness.

## Short-circuit functions¶

Short-circuit functions [5] stop as soon as the exit condition is met. These functions can yield significant speedups over functions that eagerly process the operand.

There are several instances of short-circuit functions Python library:

and also two short-circuit operators:

• and, evaluates the right side only if the left side is truthy.
• or, evaluates the right side only if the left side is falsy.

iteration_utilities includes some additional short-circuit functions:

Included in the iteration_utilities package are several helper functions that are based on normal Python code but chosen to evaluate faster than alternatives: