Glossary

Lambda

A lambda is a small anonymous function defined with the lambda keyword. Its syntax is lambda parameters: expression — it takes any number of parameters and returns the value of a single expression. Unlike def, a lambda cannot contain statements, assignments, or multiple expressions. It is limited to a single expression that is implicitly returned.

Lambdas are most useful as short callbacks or key functions passed to higher-order functions. For example, sorted(words, key=lambda w: w.lower()) sorts a list of words case-insensitively, and map(lambda x: x**2, numbers) squares each element. In these cases, a lambda avoids the overhead of defining and naming a separate function for a trivial operation.

Python's lambda is intentionally limited compared to anonymous functions in languages like JavaScript or Ruby. Guido van Rossum considered removing lambda from the language entirely in Python 3, but community resistance preserved it. The general guideline is: if a lambda is simple enough to read inline, use it; if it needs a name, a docstring, or multiple statements, define a regular function with def. Assigning a lambda to a variable (square = lambda x: x**2) is explicitly discouraged by PEP 8 — use def instead.

Related terms: Function, Closure, Decorator

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.