Learn by reading through in order

Lambda Expressions — Writing Anonymous Functions in One Line

Write one-line anonymous functions with Python lambdas and pair them with higher-order functions, all in your browser.

In the previous article on higher-order functions, you saw how to pass functions as arguments and return values. Defining a fresh function with def every time you need to hand off a callback means a one-line operation suddenly takes 3 or 4 lines.

That's where lambda expressions (lambda) come in — they let you write an anonymous function on a single line. Perfect for the small bits of logic that don't quite deserve a full def.

What Is a Lambda — Compared with def

The syntax is lambda args: expression. The result of expression becomes the return value directly, and you don't write return (in fact, doing so triggers a SyntaxError).

Unlike a normal function, a lambda has no name, so it can't be called unless you assign it to a variable. The variable name you assign it to effectively becomes the function's name.

def vs Lambda Side by Side
def versiondef add_tax(p): return int(p*1.1)lambda versionadd_tax = lambda p: int(p*1.1)compress to 1 line
A small function that takes 4 lines with def can be written in 1 line with lambda. No return is needed — the value of the expression after : is returned as-is.
# Written with def
def add_tax(price):
    return int(price * 1.1)

print(add_tax(980))   # 1078

# Same logic as a lambda (no return needed)
add_tax = lambda price: int(price * 1.1)

print(add_tax(980))   # 1078

Only Expressions Allowed — No Statements

A lambda body can only contain an expression (something that evaluates to a value). if statements, for loops, and assignments (=) won't fit. The moment you want something more elaborate, switch back to def — that's the right call.

Write a one-liner function that adds 10% sales tax to a product price.

① Build a function that takes a price and returns the tax-included amount as an integer.

② Call it with 980 yen and 2480 yen and print each result.

(When the answer is correct, the explanation will appear.)

Python Editor

Run code to see output

More Arguments, Conditional Expressions, and Defaults

Lambdas can take multiple arguments too. Just list them with commas, like lambda x, y: x * y.

You can also use default arguments the same way you do with def. To switch values based on a condition, drop a conditional expression value1 if condition else value2 into the body.

# Multiple arguments
rect_area = lambda width, height: width * height
print(rect_area(4, 5))            # 20

# Default argument (omit rate to use 0.1)
add_tax = lambda price, rate=0.1: int(price * (1 + rate))
print(add_tax(1000))              # 1100
print(add_tax(1000, 0.08))        # 1080

# Conditional expression
judge_age = lambda age: "adult" if age >= 20 else "minor"
print(judge_age(25))              # adult
print(judge_age(17))              # minor

# Return multiple values as a tuple
stats = lambda x, y: (x + y, x * y)
print(stats(3, 4))                # (7, 12)
Lambda Argument Variations
lambda x, y: x * yMultiple argumentslambda x, y=2: x**yDefault argumentlambda x: "+" if x>0 else "-"Conditional expression
lambda handles multiple arguments, default arguments, and branching with a conditional expression with the same feel as def.

Write a one-liner that returns a member tier (GOLD / SILVER / BRONZE) based on points. 1000 or above gets GOLD, 500 or above gets SILVER, and anything less is BRONZE.

① Build a function that takes points and returns the tier.

② Call it with 1500, 700, and 100, and print the result for each.

Python Editor

Run code to see output

Pairing with Higher-Order Functions — Where Lambdas Shine

Lambdas really earn their keep when you want to hand a throwaway function to a higher-order function. For instance, sorted()'s key argument is a higher-order function that takes "a function that returns the sort key from each element."

For a sort order you don't need to name and reuse, writing key=lambda x: x["price"] inline at the call site is the most natural form.

products = [
    {"name": "Notebook", "price": 480},
    {"name": "Pen",      "price": 120},
    {"name": "Eraser",   "price": 80},
]

# Sort by price ascending (pass an inline lambda as key)
cheap_first = sorted(products, key=lambda item: item["price"])
for item in cheap_first:
    print(item["name"], item["price"])
# Eraser 80
# Pen 120
# Notebook 480

# The same higher-order function process_list can switch behavior via lambda
def process_list(numbers, func):
    for n in numbers:
        print(func(n))

process_list([1, 2, 3, 4], lambda x: x ** 2)
# 1
# 4
# 9
# 16
How a Lambda Flows into sorted's key
products(list of dicts)key=lambda item: item["price"]New list sortedby price ascendingapplied to each itemsort by the key value

Sort a list of users by score, highest first. sorted() flips to descending when you pass reverse=True.

① Define users = [{"name": "Alice", "score": 78}, {"name": "Bob", "score": 92}, {"name": "Carol", "score": 65}].

② Sort with sorted(users, key=lambda u: u["score"], reverse=True) and assign the result to ranking.

③ Loop with for u in ranking: and print print(u["name"], u["score"]).

Python Editor

Run code to see output

When to Use a Lambda — and When to Avoid One

Lambdas are convenient, but using them everywhere actually hurts readability. The table below sums it up: reach for lambdas for throwaway, one-line operations, and stick with def for anything complex or reused.

SituationRecommendationReason
Pass to sorted's key, filter, maplambdaOne line conveys intent; no need for a name
One-line expressions like tax-included pricelambdaA short named function with no import needed
Logic that needs if / for / trydeflambda is expressions only; statements raise SyntaxError
Logic reused from multiple placesdefA name conveys intent and supports tests and docs
Bodies running 3+ linesdefCramming into a lambda only hurts readability

Don't Cram Everything into a Lambda

Stack three nested conditional expressions or chain a few function calls together and you end up with code that's on one line but unreadable. The moment you think "I'd love to leave a comment explaining what this lambda does," reach for def instead.

Pass an inline lambda to a higher-order function called process_list.

① Define def process_list(numbers, func): and call print(func(n)) inside for n in numbers:.

② Call process_list([1, 2, 3, 4, 5], lambda x: x ** 2) and confirm each element's square prints in order.

③ Call it again with process_list([1, 2, 3, 4, 5], lambda x: x * 10) and confirm the behavior changes just by swapping the lambda.

Python Editor

Run code to see output
QUIZ

Knowledge Check

Answer each question one by one.

Q1Which of the following is a valid lambda expression?

Q2What does this code print?
f = lambda x, y=3: x ** y
print(f(2))

Q3Which of the following is the most appropriate use of a lambda expression?