Python Reference ยท Standard Library: Data Structures and Functional Tools
functools.partial and reduce
Reference for functools.partial, partialmethod and reduce: freeze arguments, build specialized callables, fold iterables with an initial value and avoid common traps.
functools.partial creates a new callable with some arguments of an existing function already filled in. functools.reduce folds an iterable into one value by applying a two-argument function cumulatively.
Both come from functional programming. partial is handy for callbacks that expect fewer arguments than your function takes; reduce is the general fold behind sums, products and merging.
from functools import partial, reduce int_from_binary = partial(int, base=2) print(int_from_binary("101")) # 5 print(reduce(lambda a, b: a * b, [1, 2, 3, 4])) # 24
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
partial(func, /, *args, **keywords) reduce(function, iterable[, initial])
| Name | Description |
|---|---|
func |
The callable to wrap. |
args, keywords |
Positional and keyword arguments to freeze. Later calls add more positional arguments after them and can override keywords. |
function |
A function of two arguments: the accumulated value and the next item. |
iterable |
The items to fold. |
initial |
Optional starting value; also the result for an empty iterable. |
Return value: partial returns a partial object with .func, .args and .keywords. reduce returns the final accumulated value.
Raises: reduce raises TypeError for an empty iterable without initial. A partial raises whatever the wrapped function raises (usually TypeError for bad arguments).
Usage notes
- Frozen positional arguments come first.
partial(power, 2)(10)callspower(2, 10). To freeze a later parameter, use a keyword (exponent=2). - Keywords can be overridden at call time:
square(3, exponent=3)works and gives 27. - A
partialhas no__name__or docstring by default; inspect.funcinstead. It is also picklable if the wrapped function is. partialmethoddoes the same job inside a class body, where the first argument will beself.- Prefer a lambda or
defwhen the frozen call is not a simple prefix of arguments;partialis for exactly that case and avoids late-binding surprises in loops. - Always give
reducean initial value when the input could be empty, and when the result type differs from the item type. - Prefer built-ins when they exist:
sum(),math.prod(),max(),min(),all(),any()andstr.join()are clearer and often faster thanreduce. reduceis left to right:reduce(f, [a, b, c])isf(f(a, b), c). Useitertools.accumulateto see every intermediate result.