What is lambda function in Python for example?

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

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

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;

  • Yaryna Ostapchuk

    I am an enthusiastic learner and aspiring Python developer with expertise in Django and Flask. I pursued my education at Ivan Franko Lviv University, specializing in the Faculty of Physics. My skills encompass Python programming, backend development, and working with databases. I am well-versed in various computer software, including Ubuntu, Linux, MaximDL, LabView, C/C++, and Python, among others.

Leave a Comment