A lambda function in Python is an anonymous function that can be defined without a name. It is a compact and convenient way to create small, one-line functions. Here’s an example to illustrate its usage:
The syntax for creating a lambda function is as follows:
lambda arguments: expression
Code language: Python (python)
Here, lambda
is the keyword that signifies the creation of a lambda function. arguments
are the input parameters for the function, and expression
is the computation performed by the function. The result of the expression is automatically returned.
Here’s an example to demonstrate the usage of a lambda function:
# Regular function to add two numbers
def add(x, y):
return x + y
result = add(5, 3)
print(result) # Output: 8
# Equivalent lambda function to add two numbers
add_lambda = lambda x, y: x + y
result_lambda = add_lambda(5, 3)
print(result_lambda) # Output: 8
Code language: Python (python)
In this example, we have a regular function add
that takes two arguments x
and y
and returns their sum. We call the add
function with arguments 5
and 3
, which results in 8
.
The lambda function add_lambda
is equivalent to the add
function. It takes the same two arguments x
and y
and returns their sum. We call the add_lambda
function with the same arguments 5
and 3
, which also results in 8
.
Lambda functions are often used in scenarios where a small, temporary function is required, such as when passing a function as an argument to another function or when working with higher-order functions like map()
, filter()
, and reduce()
.
Read More;
- How to use for loop in JSON Python?
- What is an example of a syntax error in Python?
- What is the dash function in Python?
- How to test a class with unittest Python?
- What is an example of a runtime error?
- How to run Python script from GitLab?
- What is an example of a string in Python?
- What is RegEx in Python with example?
- What is an example of a Boolean in Python?
- What is an example of built-in and user-defined functions in Python?
- What is an example of a constructor in Python?
- What is a dictionary in Python example?