The reduce() function in Python

Cheatsheet for functools.reduce() in Python 3.

for loops seem to be more prevalent in Python.

Source

See this gist.

Background

reduce() will:

  • operate on a sequence of data
  • produce a single result

The signature of reduce() is:

reduce(function, iterable[, initializer])

where:

  • function performs the operation
  • iterable is the sequence of data
  • initializer is an optional first value for the accumulator

The signature of the function should be similar to:

def function(accumulator, value):

where accumulator is a running total and value is the current value in the collection.

Examples

Sum

Sum the items in a list:

import functools
input = (2, 1, 3)
add_to_total = lambda total, value: total + value
total = functools.reduce(add_to_total, input)

Of course, one should typically use Python’s built-in function sum.

Minimum

Find the minimum in a list:

import functools
input = (2, 1, 3)
smaller_of_two = lambda min, value: min if min < value else value
minimum = functools.reduce(smaller_of_two, input)

Of course, one should typically use Python’s built-in function min.

Maximum

Find the maximum in a list:

import functools
input = (2, 1, 3)
larger_of_two = lambda max, value: max if max > value else value
maximum = functools.reduce(larger_of_two, input)

Of course, one should typically use Python’s built-in function max.

Further Reading