typestar

reduce and partial in Python

Two functools staples: folding and pre-filling arguments.

from functools import reduce, partial

product = reduce(lambda acc, n: acc * n, [1, 2, 3, 4], 1)
running = reduce(lambda acc, n: acc + [acc[-1] + n], [1, 2, 3], [0])


def power(base, exponent):
    return base ** exponent


square = partial(power, exponent=2)
cube = partial(power, exponent=3)
nine = square(3)

How it works

  1. reduce folds a sequence into one value.
  2. partial fixes an argument to make a new function.
  3. square and cube specialize one power.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
307
Tokens
103
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 5 of 5 in Generators & itertools, step 14 of 53 in Pythonic Python.

← Previous Next →