Python Lambda

Tutorial 18 of 65 · pythondeck.com Python course

A lambda is an anonymous, single-expression function: lambda args: expr. They are convenient for short callbacks passed to sorted, map, filter, min, max and event handlers.

Lambda expressions create small anonymous functions in a single expression. They are limited to one expression body—no statements—and are most readable when passed as a short callback.

Overusing lambda hurts readability; named def functions or operator module helpers are often clearer for non-trivial logic. Lambdas excel in quick sorts and event callbacks, not in business rules you will debug next week.

Syntax: lambda args: expression returns a function object.

Common with sorted(items, key=lambda x: x[1]) and map/filter.

Cannot contain assignments, loops, or multi-line logic.

Often passed to max, min, sort key functions.

Decorators require def; lambda cannot carry docstrings meaningfully.

Equivalent def is usually easier to debug with tracebacks showing a name.

Late-binding closures: lambdas in a loop capturing loop variable share the final value—use default args lambda i=i: i to freeze binding.

PEP 8 suggests limiting lambda to one line; extract def for anything longer.

Prefer functools.partial or key=str.lower over lambda when a named function already exists.

Assigning lambda to a variable instead of using def—loses stack trace names.

Multi-step logic crammed into one unreadable lambda.

Classic loop closure bug capturing the same variable.

Using lambda where None was intended as default (callable confusion).

Use lambda only as an inline key or trivial transform.

Prefer operator.itemgetter and attrgetter for stable, named key functions.

Default-arg trick for closures in comprehensions when you truly need lambdas.

If you need comments or tests targeting the function, use def.

Reach for operator.itemgetter before lambda when sorting dict rows by a fixed key name.

Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.

The program below demonstrates sort by key. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Example: Sort by key
# Run in the REPL or save as a .py file and execute with python.
people = [("Ada", 36), ("Linus", 54), ("Grace", 85)]
print(sorted(people, key=lambda p: p[1]))

This sample walks through map / filter in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Example: map / filter
# Run in the REPL or save as a .py file and execute with python.
nums = [1, 2, 3, 4, 5]
print(list(map(lambda x: x*x, nums)))
print(list(filter(lambda x: x % 2, nums)))

Here is a hands-on illustration of closure. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.

# Example: Closure
# Run in the REPL or save as a .py file and execute with python.
def multiplier(n):
    return lambda x: x * n

triple = multiplier(3)
print(triple(10))

The program below demonstrates sorted key. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# lambda creates a small anonymous function for one-off use
rows = [("bob", 2), ("ada", 1), ("linus", 3)]  # name + rank
by_name = sorted(rows, key=lambda r: r[0])  # sort on first field
print(by_name)  # ada, bob, linus
by_rank = sorted(rows, key=lambda r: r[1])  # sort on second field
print(by_rank)  # ada, bob, linus by rank
nums = [-3, 5, -1, 2]  # signed integers
print(sorted(nums, key=lambda n: abs(n)))  # sort by magnitude
print(list(map(lambda x: x * 2, nums)))  # map with lambda
print(list(filter(lambda x: x > 0, nums)))  # positives only

This sample walks through callback hook in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Lambdas shine as short callbacks in GUI or event code
def run_twice(action):  # accept any callable
    action()  # first call
    action()  # second call

counter = {"n": 0}  # mutable closure state
run_twice(lambda: counter.update(n=counter["n"] + 1))  # increment twice
print(counter["n"])  # 2
ops = {"inc": lambda x: x + 1, "dbl": lambda x: x * 2}  # dispatch table
print(ops["inc"](4))  # 5
print(ops["dbl"](4))  # 8
transform = lambda s: s.strip().lower()  # string pipeline
print(transform("  Hello  "))  # hello

« Python Functions All tutorials Python Arrays »