Work with functionsLesson 19 of 48 · 7 min
Compose functions in the right order
Use Lambda to represent a rule and distinguish two orders of composition.
Maths refresher: Function notation
f(x) means the output of the rule f at input x. Composition feeds an output into another rule.
At , while . Function order changes the result.
A function maps permitted inputs to outputs. Composing functions means applying one rule to the result of another. The order matters: usually differs from .
SymPy Lambda represents a symbolic rule with explicit arguments. Calling it with an expression substitutes that expression into its argument position. This makes composition inspectable without creating a numerical Python function yet.
The example compares adding one then squaring with squaring then adding one. Evaluate both at the same input and compare their formulas. Keep a function’s domain in mind: a formal composition may require an output of the inner function to lie inside the outer function’s permitted inputs.
Do “add one, then square” and “square, then add one” define the same rule?
Write a prediction (optional)
Exact symbolic investigation
Select Run Python with the code unchanged.
Your saved draft is open. To use the published code, select Restore example in Tools. Use Recover draft to bring back your code.
Tools
About Python
Python and the course packages can load while you read. Each run starts with fresh user variables; imported modules stay loaded. Stop replaces the worker. Runtime details ↗
Ctrl+Enter or ⌘+Enter runs Python.
Execution error
Technical error details
Your result
Python text output
Compare with the worked example
Executed from the published Python during the site build. Your own run appears above. Build environment ↗
Worked text output
f after g: x**2 + 1 g after f: (x + 1)**2 f(g(2)): 5 g(f(2)): 9
Read the starter result
Compare f after g with g after f. The inner call happens first. The entries f(g(2)) and g(f(2)) show the effect of changing order at a shared input.
Edit and compare
Replace f = sp.Lambda(x,x+1) with f = sp.Lambda(x,2*x). Select Run Python. Compare f(g(2)) with g(f(2)). Which argument is squared in each order?
Scope. This example uses polynomial rules. Compositions involving roots or logarithms need explicit domain checks.
Try a fresh case
In , which rule receives x first?
Need a hint?
Hint 1
Start at the innermost parentheses.
Hint 2
Track the output passed to the next rule.