lambda vs def
lambda creates a short, anonymous function with one expression, while def defines a named function that can have multiple statements, default values, and a docstring.
Side-by-side comparison
#| Aspect | lambda | def |
|---|---|---|
| Number of statements in the body | A single expression | Any number of statements |
| The return keyword | Not allowed, the result is automatic | Required to return a value |
| Function name | None, it shows up as <lambda> | Its own name, visible in error tracebacks |
| Docstring | No | Yes |
| Assigning to a variable | Possible, but not recommended for complex logic | The standard way of defining a function |
| Typical use | A short argument, e.g. key= in sorted() | Reusable logic, longer functions |
Example
#students = [("Emma", 92), ("Jack", 78)]
by_score_lambda = sorted(students, key=lambda s: s[1], reverse=True)
def by_score(student):
return student[1]
by_score_def = sorted(students, key=by_score, reverse=True)
print(by_score_lambda)
print(by_score_lambda == by_score_def)Definition and usage
#Both create a function you can call, pass along as an argument, or assign to a variable. In both cases the parameters work the same way: positional, keyword, with default values.
They differ in what they can contain. After lambda there’s only a single expression, whose result is returned automatically, with no return keyword and no room for conditional statements or loops. def opens an indented block that can hold any number of statements, with its own returns, ifs, and loops, as well as a docstring. A function defined with def has its own name, which shows up in error tracebacks, while a lambda appears there as <lambda>.
Use lambda when the function is short and needed in just one place, most often as an argument, e.g. key= in sorted() or a function in map(). Use def when the logic is longer, spans more than one line, should have a name and a docstring, or when you use it in several places.
Syntax
#lambda parameters: expression
def name(parameters):
return valueMore examples
#describe = lambda score: "passed" if score >= 60 else "failed"
print(describe(75))
print(describe(40))def divide(a, b):
return a / b
divide_lambda = lambda a, b: a / b
print(divide.__name__)
print(divide_lambda.__name__)Good practices
#- If a lambda starts getting long or nested, turn it into a regular function with
def. It’ll be easier to read and to test. - When sorting by a field, also consider
operator.itemgetter(1)oroperator.attrgetter("points")instead of a lambda. - Don’t assign a lambda to a variable just to give it a name (
f = lambda x: x + 1). It’s better to writedef f(x): return x + 1directly.
Related entries
#- lambdaA short anonymous function written as a single expression.
- defDefines a function: a named block of code with parameters that you can call multiple times.
- sorted()Returns a new, sorted list built from the items of any collection.
- map()Calls a function for every item and returns an iterator of results.
- filter()Returns an iterator of items for which a function returns a truthy value.
Spotted a mistake or missing an example? Write to us.