Lambda Functions in Python
Lambda Functions
48
In Python, a lambda function is a small and anonymous function that is defined without a name. It is essentially a single-expression function that can be used wherever function objects are required. Lambda functions can have any number of arguments, but they can only have one expression.
The syntax for a lambda function in Python is:
lambda arguments: expression
Here, arguments
are the arguments to the function, and expression
is the single expression that the function returns. The result of the expression is what the lambda function returns.
For example, suppose you want to create a lambda function that squares a given number x
.
You could use the following code:
square = lambda x: x*x
This defines a lambda function that takes a single argument x
and returns the value of x*x
.
You can then call the square
function like this:
result = square(5) print(result) # output will be 25
Lambda functions are especially useful when you need to define small, simple functions for use within other functions or operations. They are often used with built-in functions like map()
, filter()
, and reduce()
.
March 25, 2023