ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 5 · 4లో పాఠం 4కోర్సులో 20/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 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది