Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 149 ยท Functions

Lambda Functions

Write small anonymous functions with Python's lambda, use them as sort keys and callbacks, learn their limits, and know when a regular def is the better choice.

Sometimes you need a function for just a moment: to tell sorted() how to compare items, or to give a button a tiny action. Writing a full def block, inventing a name and then using it once feels heavy. Python's lambda expression creates a small function right where you need it, without a name.

In this lesson you'll learn the lambda syntax, the places where lambdas shine (especially sort keys), their limitations, and the cases where a regular function is clearer.

The syntax

A lambda is written as the keyword lambda, the parameters, a colon, and a single expression:

Python
lambda parameters: expression

The value of the expression is returned automatically. There's no return keyword and no block of statements. These two definitions behave the same way:

Python def versus lambda

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The only visible difference is the name Python reports: a def function knows it's called square, while a lambda is always <lambda>. That matters in tracebacks, where a named function tells you far more about where an error happened.

Note: Assigning a lambda to a variable, as in square_lambda = lambda x: x * x, defeats the point and is discouraged by PEP 8. If you need a name, use def. The example above only shows that both produce ordinary function objects.

Parameters

Lambdas accept the same kinds of parameters as regular functions: none, several, defaults, *args and **kwargs. See Arguments for the details of each.

Python Lambda parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can even call a lambda immediately, as in (lambda x: x + 1)(5), though you'll rarely need to.

Lambdas as sort keys

The most common and most readable use of lambdas is the key argument of sorted(), list.sort(), min() and max(). The key function receives one item and returns the value to compare. Python calls it once per item.

Python Sorting with key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two techniques are worth remembering:

  • Return a tuple to sort by several fields. Python compares tuples item by item, so (year, pages) sorts by year and breaks ties with pages.
  • Negate a number to reverse one field while keeping the others ascending. For strings you can't negate, sort in two passes or use reverse=True when every field should be descending.

Python's sort is stable: items with equal keys keep their original order. That's why "Deep Waters" and "Brief Hours", both from 2019, stay in their input order in the first result.

Lambdas as callbacks

Any function that accepts another function can take a lambda. Here are a few built-ins and patterns you'll meet often (they get a full lesson in Higher-Order Functions):

Python Lambdas as arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The dictionary of lambdas is a neat way to map names to small behaviors without a long if/elif chain. The div lambda shows that you can use a conditional expression (x if condition else y) inside a lambda, because it's still a single expression.

That said, for map and filter, a list comprehension is usually clearer in Python:

Python
with_tax = [round(p * 1.2, 2) for p in prices]
cheap = [p for p in prices if p < 10]

Other handy places for lambdas

A few more patterns come up often enough to recognize on sight:

  • Picking from a dictionary by value. max(scores, key=scores.get) returns the key with the highest value, and sorted(scores.items(), key=lambda pair: pair[1]) sorts the key-value pairs by value.
  • Default factories. collections.defaultdict(lambda: "unknown") calls the lambda to create a value for every missing key (see collections).
  • Deferred work. Passing lambda: expensive_report() lets another function decide whether and when to run the expensive call, instead of running it up front.
Python
scores = {"Ana": 82, "Ben": 95, "Chen": 77}
print(max(scores, key=scores.get))                        # Ben
print(sorted(scores.items(), key=lambda pair: pair[1]))   # lowest first

Notice that scores.get needs no lambda at all: it's already a function that takes a key and returns a value. Before wrapping something in a lambda, check whether an existing function or method already does the job.

What lambdas can't do

A lambda body must be one expression. That rules out:

  • statements such as if blocks, for and while loops, try/except, with and assignments with =;
  • docstrings and type annotations;
  • multiple lines of logic.

You can call functions that print or change things, and the walrus operator := works inside an expression, but cramming logic into a lambda quickly becomes unreadable. If you're tempted, write a def.

Python When def is better

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both versions produce the same order, but only one of them explains itself. A good rule of thumb: if a lambda doesn't fit comfortably on one line, or you'd want to explain it with a comment, give it a name.

Lambdas and late binding

Lambdas are closures, just like nested def functions, so they look up outer variables when they run, not when they're created. As you saw in Scope, lambdas built in a loop all share the loop variable unless you freeze it with a default argument:

Python
handlers = [lambda: print(n) for n in range(3)]         # all print 2
handlers = [lambda n=n: print(n) for n in range(3)]     # print 0, 1, 2

Alternatives in the standard library

For the most common key functions, the operator module offers ready-made, slightly faster versions:

  • operator.itemgetter("year") works like lambda d: d["year"], and itemgetter("year", "pages") returns a tuple of both.
  • operator.attrgetter("name") works like lambda obj: obj.name.
Python
from operator import itemgetter

by_year = sorted(books, key=itemgetter("year"))

Either style is fine. Lambdas are more flexible; itemgetter is a little more declarative.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (lambda a, b=2: a * b)(5) evaluate to?

    The lambda is called with a=5, and b uses its default of 2, so the result is 10.
  2. 2. Which of these can appear in a lambda body?

    A lambda body is a single expression. Conditional expressions are expressions; loops, try blocks and = assignments are statements.
  3. 3. How do you sort a list of (name, age) tuples by age, oldest first?

    The key returns the age (index 1), and reverse=True puts the largest first. The key must be passed by keyword as a function.
  4. 4. Why does PEP 8 discourage area = lambda w, h: w * h?

    If you're naming it anyway, def is clearer and the function reports its real name instead of <lambda> in error messages.

Summary

  • lambda params: expression creates a small anonymous function that returns the expression's value.
  • Lambdas accept defaults, *args and **kwargs, but the body must be a single expression: no statements, docstrings or annotations.
  • Their best use is short, inline functions such as key= for sorted(), min() and max(). Return a tuple to sort by several fields.
  • Prefer list comprehensions over map/filter with lambdas, and prefer def whenever you'd name the function or the logic grows.
  • Lambdas are closures: bind loop variables with a default argument. operator.itemgetter and attrgetter are handy alternatives.

Next: Recursion, where functions solve problems by calling themselves.