Python · Functions & Decorators

Lambda function

Mediumlambdaanonymous-functionsortedfunctions

Interview question

What is a lambda function in Python?

How to answer

The short answer

A lambda is an anonymous, single-expression function. Handy for short callbacks to sorted, map, filter, or any API that wants a callable.

Form: lambda params: expression

Lambdas cannot contain statements (if blocks, assignments, multi-line logic). For anything non-trivial, define a named def.

Python
add = lambda x, y: x + y
print(add(2, 3))  # 5

rows = [{"name": "b", "score": 3}, {"name": "a", "score": 10}]
rows_sorted = sorted(rows, key=lambda r: r["score"], reverse=True)

# Equivalent named function (often clearer)
def score_of(row):
    return row["score"]

rows_sorted = sorted(rows, key=score_of)

# Conditional expression is allowed
label = lambda n: "even" if n % 2 == 0 else "odd"

Interview stance: Lambdas are syntactic sugar for tiny functions. Readability beats cleverness; many style guides discourage assigning complex lambdas to names.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill