Advanced Python Techniques

Lambda Functions: Small, Anonymous, One-Line

5 min read

A function without the ceremony

You already know how to write a function with def — you covered that back in Functions: Writing Reusable Code. Most of the time, def is exactly what you want: a named, reusable block of logic.

But sometimes you need a function for exactly one moment — passed straight into another function and never used again. Writing a full def block, giving it a name you'll never call directly, feels like overkill for something that small. Python's answer is the lambda: a small, anonymous function that returns a single expression, defined in one line, with no def and no name required.


Anatomy of a lambda

Diagram — Anatomy of a Lambda Function

doubler = lambda x: x*2lambdastarts everylambda functionargumentscomma-separated,zero or more: (colon)separates argsfrom expressionexpressionevaluated andreturned automaticallyNo return keyword needed — a lambda always returns the value of its single expression.doubler(5) evaluates 5*2 and hands back 10.

Every lambda follows the same shape: lambda arguments: expression.

  • lambda — the keyword that starts every lambda function
  • arguments — zero or more parameters, comma-separated, just like a regular function
  • : — separates the arguments from the expression
  • expression — a single expression, automatically evaluated and returned — there's no return keyword
doubler = lambda x: x*2

print(doubler(2))   # 4
print(doubler(5))   # 10

Output:

4
10

The same thing, written with def

A lambda doesn't do anything a regular function can't. doubler above is functionally identical to:

def doubler(x):
    return x*2

print(doubler(2))   # 4
print(doubler(5))   # 10

Output:

4
10

The difference is entirely about form, not behavior: def needs a block with a name and a return statement; lambda squeezes the same logic into a single expression with no name attached. That trade-off is the whole point of a lambda — brevity for a function that's too small or too short-lived to deserve a full definition.


Multiple arguments

A lambda can take more than one argument — just separate them with commas, exactly like def:

mul = lambda x, y: x*y
print(mul(2, 5))    # 10

add = lambda x, y, z: x+y+z
print(add(2, 5, 10))   # 17

Output:

10
17

Default arguments

Lambdas support default values the same way regular functions do — assign one with =, and calls that omit the argument fall back to it:

incrementer = lambda x, y=1: x+y

print(incrementer(5, 3))   # 8
print(incrementer(5))      # 6 — y falls back to its default of 1

Output:

8
6

Returning multiple values

A lambda's expression can be a tuple, which is Python's way of returning more than one value at once. Unpack it with multiple assignment on the way out:

findSquareCube = lambda num: (num**2, num**3)

x, y = findSquareCube(2)
print(x)   # 4
print(y)   # 8

Output:

4
8

(num**2, num**3) is a single expression — a tuple literal — so it's perfectly legal inside a lambda even though it's really packing two values together.


if/else inside a lambda

A lambda's body has to be one expression, so it can't contain a full if/elif/else statement the way a def function can. But Python's conditional expressionvalue_if_true if condition else value_if_false — is itself a single expression, which makes it the natural fit for adding branching logic to a lambda:

findMin = lambda x, y: x if x < y else y

print(findMin(2, 4))     # 2
print(findMin('a', 'x')) # a

Output:

2
a

This reads left to right: "return x, if x is less than y — otherwise return y." It works on any type that supports <, including strings, which compare alphabetically.


When to actually use a lambda

Lambdas shine as throwaway arguments to other functions — especially ones like sorted(), max(), or map() that expect a function as input:

people = [("Arjun", 34), ("Karun", 29), ("Sana", 41)]

# Sort by age (the second item in each tuple)
people.sort(key=lambda person: person[1])
print(people)

Output:

[('Karun', 29), ('Arjun', 34), ('Sana', 41)]

Here, key=lambda person: person[1] tells sort() exactly what to compare, without the ceremony of defining and naming a separate function you'll only ever use in this one call.

What a lambda is not good for is replacing def for anything with real logic. Python's official style guide (PEP 8) specifically recommends against writing doubler = lambda x: x*2 and assigning it to a name — if a function is important enough to have a name, def doubler(x): return x*2 is clearer and easier to debug (it shows up properly in tracebacks; a lambda just says <lambda>). Reach for a lambda when the function is small, is used once, and is passed directly as an argument — not as a general substitute for def.


Key takeaway

A lambda — lambda arguments: expression — is a compact, unnamed function that always returns the value of its single expression. It supports multiple arguments, default values, tuple returns, and conditional expressions, just like a regular function. Its best use is as a quick, inline argument to another function, like sort()'s key=; for anything you'll name and reuse, prefer def.


What's next?

Lambdas get most of their real power in combination with other functions that expect one as an argument. Next up: map(), filter(), and reduce() — three tools built specifically to take a lambda (or any function) and apply it across an entire collection at once.