If you're like me, you enjoy browsing through the list of Python's built-ins to find better ways to do high-level things more concisely.

If you're even more like me, you stop to scratch your chin every time you come across reduce, a nice way to do some functional programming in Python. If you're unfamiliar with reduce, it goes a little something like this:

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).

"Hmmm," you think, "I bet I could use this for something. But what?!" Well, today I submitted this recipe to the ActiveState Python Cookbook. It provides a few ideas for real-life situations where using reduce is both helpful and concise.

Here's an example:

import operator
def factorial(n):
    """Calculate n factorial"""
    return reduce(operator.mul, range(2, n+1), 1)

Usage:

>>> factorial(10)
3628800

Another one:

def intersection(*sets):
    """Get the intersection of all input sets"""
    return reduce(set.intersection, sets)

Usage:

>>> a = set([1, 2, 3, 4, 5])
>>> b = set([5, 6, 3, 7])
>>> c = set([8, 7, 5])
>>> intersection(a, b, c)
set([5])

If you have any of your own reduce recipes, post them here or to the Cookbook recipe. Happy reducing!