Skip to main content
eLearner.app
Module 5 · Lesson 4 of 420/36 in the course~10 min
Module lessons (4/4)

Lambda and higher-order functions

A lambda is an anonymous function, defined on a single line. Syntax:

Python
lambda parametri: espressione

Equivalent to def, but more concise and a good fit for "throwaway" functions to pass to other functions.

Python
quadrato = lambda x: x ** 2
quadrato(5)    # 25

# equivalent to:
def quadrato(x):
    return x ** 2

Differences vs def

Aspectdeflambda
namerequiredanonymous
bodymultiple statementsa SINGLE expression
returnexplicitimplicit (the expression)
docstringyesno

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.

Python
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:

Python
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 age

Other typical uses: min(...), max(...), filter(...), map(...).

Python
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

Exercise#python.m5.l4.e1
Attempts: 0Loading…

Given the list `words = ['banana', 'kiwi', 'mela', 'fragola']`, sort it by ascending length into `by_length`. Evaluate `by_length`.

Loading editor…
Show hint

key=len (or lambda p: len(p)).

Solution available after 3 attempts

Review exercise

Exercise#python.m5.l4.e2
Attempts: 0Loading…

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`.

Loading editor…
Show hint

lambda p: p[1]

Solution available after 3 attempts

Additional challenge

Exercise#python.m5.l4.e3
Attempts: 0Loading…

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.

Loading editor…
Show hint

Write is_even = lambda x: x % 2 == 0 and then call is_even(8).

Solution available after 3 attempts