A powerful tool for creating anonymous functions. Lambda functions allow us to create functions on the fly without needing to define them with a name.
Lambda functions, also known as anonymous functions, are defined using the lambda
keyword. They are typically used for small, one-line functions where a named function would be overkill.
The basic syntax of a lambda function is as follows:
lambda arguments: expression
Here's an example of a lambda function that adds two numbers:
add = lambda x, y: x + y
In this example, we create a lambda function called add
that takes two arguments x
and y
and returns their sum. The lambda function can be called just like any other function:
result = add(3, 5)
print(result) # Output: 8
In this case, calling add(3, 5)
will return the sum of 3 and 5, which is 8.
Lambda functions can also be used directly as arguments to other functions. This is particularly useful when working with higher-order functions that expect functions as arguments.
The main difference between lambda functions and named functions is that lambda functions do not require a separate def statement to define them. Instead, they can be defined directly where they are needed.
Lambda functions are commonly used for simple operations and are more concise compared to named functions. However, they have some limitations:
- Lambda functions can only contain a single expression.
- Lambda functions cannot include statements or multiple lines of code.
- Lambda functions are typically used for short, one-line operations.
Named functions, on the other hand, can be used for more complex operations that require multiple lines of code and statements. Named functions are defined using the def
keyword and can be called by their defined name.
Here's an example to illustrate the difference between a lambda function and a named function:
# Lambda function
multiply = lambda x, y: x * y
print(multiply(3, 5)) # Output: 15
# Named function
def multiply_func(x, y):
return x * y
print(multiply_func(3, 5)) # Output: 15
In this example, both the lambda function multiply
and the named function multiply_func
perform the same operation: multiplying two numbers. The output of both function calls is 15.