functools.reduce

folding a sequence into one value

20 min · interactive lesson with runnable code and 5 graded exercises.

What you'll be able to do

  • Explain the accumulator and the (acc, item) -> new_acc step
  • Use an initializer — and know why empty input needs one
  • Know when sum, max, any or a loop is better
  • Avoid quadratic concatenation inside reduce

The full lesson is free with an account.

What reduce does

Useful folds

When not to use it

The quadratic trap

Common pitfalls