lambda
lambda
keyword.
Lambda functions can have any number of arguments but only one expression.
They are often used as a concise way to create simple functions without needing to
define a separate function using the def keyword.
::Syntax::
lambda arguments : expression
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
multiply = lambda x, y: x * y
print(multiply(3, 5)) # Output: 15
Squaring a number:
square = lambda x: x ** 2
print(square(3)) # Output: 9
is_even = lambda x: x % 2 == 0
print(is_even(4)) # Output: True
print(is_even(3)) # Output: False
Reversing a string:
def square(x):
return x ** 2
print(square(3)) # Output: 9
Using a Lambda Function:
square_lambda = lambda x: x ** 2
print(square_lambda(3)) # Output: 9
In both cases, we're defining a function to square a number (x ** 2). Here's the
difference:
The normal function (square) is defined using the def keyword and has a name
(square).
The lambda function (square_lambda) is defined using the lambda keyword and doesn't
have a name (hence, it's anonymous).
Both functions behave the same way when called with the same arguments.
In this example, the lambda function is more concise, but the trade-off is that it
lacks a name,
making it less readable for more complex operations or when the logic inside the
function becomes longer.
However, for simple operations like this, lambda functions can be quite handy and
reduce code verbosity.