Lambda functions in Python

Python : Lambda functions

Lambda functions are also known as anonymous functions in Python. These are a one-line expression of a function that does not require a name. They are used to simplify code and make it more readable by reducing the number of lines of code.

Lambda Functions Syntax in Python

The arguments are the input variables and the expression is the output value of the function.

lambda arguments: expression

Lambda Functions Example in Python

sum = lambda x, y: x + y
print(sum(5, 10)) # Output: 15

Here, lambda x, y: x + y creates a lambda function that takes two arguments x and y and returns their sum. This lambda function is then assigned to the variable sum and called with arguments 5 and 10.

Benefits of using Lambda Functions in Python:

  1. They are shorter than regular functions and can be used to write more concise code.
  2. They can be used as arguments for other functions.
  3. They can be used to return functions.

Here is another example

def my_func(n):
    return lambda x : x * n

double = my_func(2) # Output: 10
triple = my_func(3) # Output: 15

  • lambda functions in Python are a powerful tool for simplifying code and making it more concise. They can be used as arguments for other functions and can even be used to return functions.