In Python, a lambda function is a small anonymous function that can take any number of arguments, but can only have one expression. Lambda functions are commonly used in functional programming to create a concise way of defining simple functions without the need to define a full function with a name.
Syntax
The arguments part of the lambda function is where you specify any arguments that the function will take. This can be a single argument or multiple arguments, separated by commas.
The expression part of the lambda function is where you specify the computation that the function will perform. This can be any valid Python expressio
Here’s an example of a lambda function that takes two arguments and returns their sum:
sum = lambda x, y: x + y
In this example, lambda x, y:
defines the function with two arguments, and x + y
is the expression that the function returns.
You can use the lambda
keyword to define a lambda function in Python, like this:
lambda arguments: expression
For example, here’s a lambda function that squares a number:
square = lambda x: x**2
You can call this function just like any other function, passing in a value for x
:
result = square(4)
print(result)
Output
16