In Python, both def and lambda are used to create functions, but they serve different purposes. Understanding the differences between them helps to choose the right approach for different programming scenarios.
Def keyword
def keyword is used to define a regular function. Functions created with def can contain multiple statements, support complex logic such as loops and conditional statements, and may optionally return a value using the return statement.
def square(n):
return n * n
print(square(5))
Output
25
Explanation: square() function is created using the def keyword. When square(5) is called, it returns 25 using the return statement.
Lambda keyword
lambda keyword is used to create small, anonymous functions. A lambda function can accept multiple arguments but can contain only a single expression.
square = lambda n: n * n
print(square(5))
Output
25
Explanation: lambda function lambda n: n * n takes one argument n and returns its square. Since a lambda function consists of a single expression, the result is returned automatically without using the return keyword.
The table below highlights the key differences between def functions and lambda functions.
| Feature | def | lambda |
|---|---|---|
| Definition | Created using the def keyword | Created using the lambda keyword |
| Name | Has a function name | Anonymous by default (can be assigned to a variable) |
| Function Body | Can contain multiple statements | Can contain only one expression |
| Return | Uses the return keyword | Returns the expression automatically |
| Complexity | Suitable for complex logic | Best for simple one-line operations |
| Readability | Easier to read and maintain | Best for short, concise code |
| Common Use | Reusable functions | Temporary or inline functions |