python
  1. python-lambda-functions

Python Lambda Functions

Lambda functions are also called anonymous functions. They are a way to create a small function in a single line of code without a name. Lambda functions can have any number of arguments, but they can have only one expression.

Syntax

The syntax for lambda function is as follows:

lambda arguments: expression

Example

# Using a regular function to add two numbers
def add_numbers(x, y):
    return x + y

# Using lambda function to add two numbers
add = lambda x, y: x + y

print(add_numbers(2, 3))
print(add(2, 3))

Output

5
5

Explanation

In the example above, we have defined two functions to add two numbers. add_numbers() is a regular function that takes two arguments x and y and returns their sum.

add is a lambda function that takes two arguments x and y and returns their sum. We have defined add using the lambda syntax.

Both add_numbers() and add() will give the same output.

Use

Lambda functions are used when we want to create a small function that can be used only once and does not require a name. We can use lambda functions with built-in functions such as map(), filter(), and reduce().

Important Points

  • Lambda functions are also called anonymous functions.
  • They can have any number of arguments, but can only have one expression.
  • Lambda functions are used when we want to create a small function that can be used only once and does not require a name.
  • Lambda functions can be used with built-in functions such as map(), filter(), and reduce().

Summary

Lambda functions are a way to create a small function in a single line of code without a name. They are used when we want to create a small function that can be used only once and does not require a name. Lambda functions can have any number of arguments, but can only have one expression. They can be used with built-in functions such as map(), filter(), and reduce().

Published on: