The lambda
keyword in Python is used to create small, anonymous functions. These functions are defined without a name and consist of a single expression. lambda functions are often used as a concise way to write short, throwaway functions.
Example
square = lambda x: x ** 2
print(square(4))
Output:
Syntax
lambda arguments: expression
arguments
: A comma-separated list of arguments that the function takes.expression
: A single expression whose result is returned.
Why Use lambda?
- Conciseness: Write short functions in a single line of code.
- Throwaway Functions: Ideal for functions that are used once or for a short duration.
- Used in Higher-Order Functions: Commonly used with functions like map(), filter(), and sorted().
Common Examples
1. Basic Lambda Function
add = lambda x, y: x + y
print(add(3, 5))
Output:
8
2. Using Lambda with map()
numbers = [1, 2, 3, 4]
squares = map(lambda x: x ** 2, numbers)
print(list(squares))
Output:
[1, 4, 9, 16]
3. Using Lambda with filter()
numbers = [10, 15, 20, 25, 30]
divisible_by_5 = filter(lambda x: x % 5 == 0, numbers)
print(list(divisible_by_5))
Output:
[10, 15, 20, 25, 30]
4. Using Lambda with sorted()
points = [(1, 2), (3, 1), (5, 0)]
sorted_points = sorted(points, key=lambda x: x[1])
print(sorted_points)
Output:
[(5, 0), (3, 1), (1, 2)]
5. Inline Lambda in Function Calls
print((lambda x, y: x * y)(4, 5))
Output:
20
Key Notes
- Anonymous Functions:
lambda
functions are unnamed and often used for short, one-off tasks.- They are not a replacement for def but a tool for specific use cases.
- Single Expression Only:
- A
lambda
function can only contain a single expression, unlike regular functions defined with def.
- A
- Readable Use:
- Overusing
lambda
can make code harder to read. Use them judiciously and prefer def for complex logic.
- Overusing
When to Use lambda?
- Short-Lived Functions:
- For single-use, small functions, like sorting keys or applying transformations in a list.
- Higher-Order Functions:
- When using map(), filter(), or reduce() to apply a specific transformation or condition.
- Simpler Syntax:
- To avoid defining full functions when only a single expression is required.