We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Map, Filter, and Reduce Review

Higher-order functions like map, filter, and reduce allow us to avoid stateful iteration and mutation of variables.

Take a look at this imperative code that calculates the factorial of a number:

def factorial(n: int) -> int:
    # a procedure that continuously multiplies
    # the current result by the next number
    result: int = 1
    for i in range(1, n + 1):
        result *= i
    return result

Here's the same factorial function using reduce:

import functools


def factorial(n: int) -> int:
    return functools.reduce(lambda x, y: x * y, range(1, n + 1))

In the functional example, we're just combining functions to get the result we want. There's no need to reassign variables or keep track of the program's state in a loop.

A loop is inherently stateful! Depending on which iteration you're on, the i variable has a different value.