Lambda Functions in Python
A lambda function in Python is a small and anonymous function. It has no name, and it's used for simple operations that are done in one line.
It is useful when we want to write short functions without using the def keyword.
Syntax:
lambda arguments : expression
Note: The result of the expression is automatically returned.
Example 1: Lambda to add two numbers
add = lambda a, b: a + b
print("Sum is:", add(5, 3))
Output:
Sum is: 8
Explanation:
lambda a, b: a + bdefines an anonymous function.- It takes two inputs and returns their sum.
- The function is assigned to
addand called usingadd(5, 3).
Example 2: Lambda with no variable assignment (used directly)
print((lambda x: x * x)(6))
Output:
36
Explanation:
- The lambda function is created and used directly.
- It takes input
6and returns6 × 6 = 36.
Where is Lambda used?
- Inside
map(),filter(), orreduce()functions - When a small function is needed temporarily
- To reduce lines of code
Summary Table:
| Term | Description | Example |
|---|---|---|
lambda |
Creates an anonymous function | lambda a, b: a + b |
| Used for | Short, one-line functions | Inside map(), filter() |
Key Points to Remember:
- Lambda functions are also called anonymous functions.
- They are used for short operations written in a single line.
- They do not need the
returnkeyword explicitly. - Syntax:
lambda arguments : expression