Перейти до основного вмісту
eLearner.app
Модуль 5 · Урок 4 із 420/36 у курсі~10 min
Модульні уроки (4/4)

Лямбда-функції та функції вищого порядку

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

вправи#python.m5.l4.e1
Спроби: 0Завантаження…

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

Завантаження редактора…
Показати підказку

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

Рішення доступне після 3 спроб

Review exercise

вправи#python.m5.l4.e2
Спроби: 0Завантаження…

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

Завантаження редактора…
Показати підказку

lambda p: p[1]

Рішення доступне після 3 спроб

Additional challenge

вправи#python.m5.l4.e3
Спроби: 0Завантаження…

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.

Завантаження редактора…
Показати підказку

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

Рішення доступне після 3 спроб