Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. Lambda function

Python · Functions & Decorators

Lambda function

Mediumpython-13
lambdaanonymous-functionsortedfunctions

Question

What is a lambda function in Python?

Solution

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.

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.

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext