Higher-Order Functions & functools

advanced level · ~20 min · Module 17: Functional Programming Concepts

Compose clean functional pipelines and use functools.lru_cache for memoization.

Learning objectives

  • Use functools.reduce for custom accumulators
  • Cache expensive recursive calls with @lru_cache

Lesson material

Memoization with lru_cache

@lru_cache caches function return values based on input arguments.

Example code

from functools import lru_cache

@lru_cache(maxsize=None)
def fib_fast(n):
    if n < 2:
        return n
    return fib_fast(n - 1) + fib_fast(n - 2)

print("Fibonacci(35):", fib_fast(35))

Practice exercise: Reduce Accumulator

Use `functools.reduce` and lambda to compute the product of list `[1, 2, 3, 4, 5]`. Print the product.

Test yourself with the Module 17: Functional Programming Concepts quiz →

View the full Python curriculum →