Lambda
In one line
A lambda is a small anonymous function defined in a single expression, written as lambda params: expression.
In simple words
A lambda is an anonymous (nameless) function defined in a single expression. The syntax is lambda parameters: expression. The expression is evaluated and returned automatically — no return keyword needed.
Lambdas are useful for short, throwaway functions, especially as arguments to sorted(), map(), filter(), and reduce(). They are more concise than a full def for simple operations.
Lambdas are limited to a single expression — you cannot have statements, multiple lines, or complex logic. For anything more than a simple expression, use a regular def function for readability.
Example
# Basic lambda
square = lambda x: x ** 2
print(square(5)) # 25
# As a sort key
people = [("Alice", 30), ("Bob", 25)]
people.sort(key=lambda p: p[1])
print(people) # [('Bob', 25), ('Alice', 30)]
# With map and filter
nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
print(doubled, evens) # [2, 4, 6, 8, 10] [2, 4]Lambdas are single-expression anonymous functions, useful for sort keys, map, and filter.
Common confusions
Confused with: def function
The difference: A lambda is a single-expression anonymous function. A def function can have multiple statements, docstrings, and complex logic. Use lambda for simple one-liners; use def for anything complex.
Related terms
Related Resources
Related Lessons
- Lambda Functions
Lambda functions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.