Loading...
Higher-order operations describe patterns of transformation. Follow the order of function application and distinguish changing every element from selecting some elements or combining them.
What you'll be able to do
For f:A→B and g:B→C, composition g∘f applies f first and then g, giving A→C. Reversing the order can change the result or be invalid if the types do not fit. Read composition from the value’s path rather than from ordinary left-to-right prose.
With f(x)=x+2 and g(x)=3x, g(f(4))=18 while f(g(4))=14. A composed function can hide the intermediate value from the caller while preserving a clear input–output contract. Side effects can make reasoning more complicated than this pure mathematical model.
Map applies a function to each input element, producing corresponding results. Filter retains elements meeting a predicate; it does not replace every element by the predicate’s Boolean answer. In Python 3, map and filter produce iterators, so list(...) is used in the examples to collect visible list results.
Higher-order means a function takes a function argument, returns a function, or both. A mapping callback can still perform side effects in a general-purpose language; the operation name alone does not guarantee purity. Clear pure transformations are easier to reason about and distribute.
A reduce or fold repeatedly combines an accumulator with elements. An initial value defines the empty-input result and the starting context. Summing [1,2,3] from zero yields six; subtracting in a left fold from ten gives ((10-1)-2)-3=4.
Order matters for non-associative operations such as subtraction and floating-point accumulation. Reordering or parallelising a reduction requires attention to the combining operation’s properties. Do not assume every fold can be rearranged without changing the result simply because the values are numerical.
from functools import reduce
values = [1, 2, 3, 4]
print(list(map(lambda x: x * x, values)))
print(list(filter(lambda x: x % 2 == 0, values)))
print(reduce(lambda total, x: total + x, values, 0))Scroll horizontally to see the full code or table.Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.