lambda (anonymous function)
Creates a small anonymous function for short, single-expression logic.
lambda arg1, arg2: expressionThis static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Creates a small anonymous function for short, single-expression logic.
In Python, a lambda function is a small, anonymous function defined with the lambda keyword rather than def. These functions are restricted to a single expression and cannot contain statements such as assignments or return. Technically, a lambda produces a function object at runtime, meaning its performance is virtually identical to a named function. However, lambdas lack a __name__ attribute for debugging unless manually assigned. A critical edge case is 'late binding' in closures: if a lambda is defined inside a loop and references the loop variable, it will use the value of that variable at the time the function is called, not when it was defined. To fix this, one must pass the variable as a default argument. When using lambdas within filter(), remember that Python's truthy coercion applies: values like 0, None, or empty strings are discarded. For sorting operations, lambda is frequently used as a key; note that list.sort() mutates the original list and returns None, while sorted() returns a new list reference. For reliable date sorting, ensure lambdas return ISO 8601 strings or numeric timestamps.
Quick reference
Syntax
lambda arg1, arg2: expression
Inputs
Parameters
See it in practice
Examples
Sorting Complex Objects
items = [{'id': 1, 'date': '2023-05-20'}, {'id': 2, 'date': '2021-11-10'}]
items.sort(key=lambda x: x['date'])
print(items)[{'id': 2, 'date': '2021-11-10'}, {'id': 1, 'date': '2023-05-20'}]
Uses a lambda as a key to sort a list of dictionaries by a date string. Note that list.sort() mutates the original list in place.
Filtering with Truthy Coercion
mixed_data = [0, 1, False, True, 'python', '']
# predicateFn checks for truthiness
result = list(filter(lambda x: x, mixed_data))
print(result)[1, True, 'python']
The lambda acts as a predicateFn. Truthy coercion keeps non-zero numbers and non-empty strings, but removes 0 and empty strings.
Fixing Late Binding in Loops
# Use default argument to capture value at definition time
multipliers = [lambda x, i=i: x * i for i in range(3)]
results = [m(10) for m in multipliers]
print(results)[0, 10, 20]
By setting i=i, the current value of the loop index is bound to the lambda immediately, avoiding the late binding closure bug.
Debug faster
Common Errors
SyntaxError
Cause: Attempting to include statements like 'return' or multiple lines inside a lambda expression.
Fix: Remove the 'return' keyword or convert the lambda into a named 'def' function if multiple lines are required.
invalid = lambda x: return x + 1NameError (Late Binding)
Cause: Using a loop variable inside a lambda where the lambda is called after the loop finishes.
Fix: Capture the variable at definition time using a default argument (e.g., lambda i=i: ...).
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # Outputs [2, 2, 2]Runtime support
Compatibility
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Creates a small anonymous function for short, single-expression logic.
arg1: First argument. arg2: Second argument. expression: Single expression whose result is returned.
SyntaxError: Remove the 'return' keyword or convert the lambda into a named 'def' function if multiple lines are required. NameError (Late Binding): Capture the variable at definition time using a default argument (e.g., lambda i=i: ...).