Module lessons (4/4)
Lambda and higher-order functions
A lambda is an anonymous function, defined on a single line. Syntax:
lambda parametri: espressioneEquivalent to def, but more concise and a good fit for "throwaway"
functions to pass to other functions.
quadrato = lambda x: x ** 2
quadrato(5) # 25
# equivalent to:
def quadrato(x):
return x ** 2Differences vs def
| Aspect | def | lambda |
|---|---|---|
| name | required | anonymous |
| body | multiple statements | a SINGLE expression |
| return | explicit | implicit (the expression) |
| docstring | yes | no |
No return inside a lambda: the value of the expression IS the result.
When to use lambda
Almost always: as a key argument for sorting or selection functions.
parole = ["banana", "kiwi", "mela", "fragola"]
sorted(parole, key=len)
# ['kiwi', 'mela', 'banana', 'fragola']key=len tells sorted: "to compare two elements, use their length". For
custom criteria, use lambda:
utenti = [
{"nome": "Ada", "eta": 36},
{"nome": "Linus", "eta": 54},
{"nome": "Grace", "eta": 85},
]
per_eta = sorted(utenti, key=lambda u: u["eta"])
# sorted by ascending ageOther typical uses: min(...), max(...), filter(...), map(...).
nums = [-3, 1, -4, 1, -5, 9]
max(nums, key=lambda n: abs(n)) # -5 (maximum by absolute value)Higher-order functions
A function is higher-order if it accepts a function as an argument or
returns one. sorted, max, filter, map are higher-order. Lambda
exists precisely to make higher-order calls easier.
When to avoid lambda functions
Lambda functions are useful for short, throwaway operations (like quick sorting). However, if you find yourself assigning a lambda to a variable (e.g. double = lambda x: x * 2), it is generally preferred to use a standard def block for readability and debugging purposes (since functions defined with def retain their real names in error tracebacks).
Try it
Given the list `words = ['banana', 'kiwi', 'mela', 'fragola']`, sort it by ascending length into `by_length`. Evaluate `by_length`.
Show hint
key=len (or lambda p: len(p)).
Solution available after 3 attempts
Review exercise
Given the list of tuples `points = [(1, 5), (3, 2), (2, 4)]`, sort them by the SECOND element in ascending order and assign to `by_y`. Evaluate `by_y`.
Show hint
lambda p: p[1]
Solution available after 3 attempts
Additional challenge
Define an anonymous `lambda` function that takes a number `x` and returns `True` if the number is even, and `False` otherwise. Assign the lambda to the variable `is_even` and test it with `is_even(8)` as the last line.
Show hint
Write is_even = lambda x: x % 2 == 0 and then call is_even(8).
Solution available after 3 attempts