Python Reduce

Python Reduce #

reduce() from the (functools module) takes a function and bunch of things (iterables, like lists, tuples, sets, etc.) as arguments, and returns a single value.

What does it do? reduce() applies the function to the first two elements of the things, then applies the function to that first result and the next thing, then takes that result and applies it to the next thing, and so on.

from functools import reduce

numbers = [1, 2, 3]

results = reduce(lambda x, y: x + y, numbers)
# 6

Use cases:

  • Find the minimum or maximum
  • Check if everything is True