Python Lambda Function

In this lesson, you’ll discover more about anonymous functions, referred to as lambda functions. You’ll find out what they are, how to utilize them, and their syntax (with examples).

What is Lambda Function?

A function doesn’t need to have a name called Lambda Function. Using the ‘lambda’ keyword, a lambda expression in Python, enables us to write a lambda function. In Python, the lambda keyword is used to define anonymous functions rather than the def keyword, which is used for conventional functions. Anonymous functions are another name for lambda functions.

Basic Syntax

Addition = lambda param1, param2: param1 + param2

# Call Addition function

print Addition(10, 20)

Any number of parameters, but only one expression, can be passed to a lambda function. The expression is assessed and given a result. Wherever function objects are necessary, you can use the lambda function.

Example

AdditionFun = lambda intVar1, intVar2: intVar1 + intVar2
print AdditionFun(2, 5)
print AdditionFun(12, 1)
recursiveFunc

Output

7

The lambda function in the program above is lambda intVar: intVar + 2. In this case, the evaluated and returned expression is intVar + 2, where intVar is the argument.

It doesn’t have a name. It gives back a function object with the identification double. Now, we can refer to it as a typical function. The assertion lambda intVar1, intVar2: intVar1 + intVar2 is equal to

def AdditionFun (x):
return intVar1 + intVar2

Python’s use of the Lambda Function

Along with built-in functions like filter(), map(), and others, lambda functions are employed. Lambda functions are used when a nameless function is needed for a brief duration. We use it as an argument to a higher-order function in Python (a function that takes other functions as arguments).

Example of using a map()

Python’s map() method accepts both a function and a list. A new list is returned that contains items returned by that function for each item once the function is invoked with the entire list of items. Here is an illustration of how to divide every item in a list using the map() method.

Example

firstList = [
    2,
    4,
    6,
    8,
    10,
    12,
    ]
doubleList = list(map(lambda i: i / 2, firstList))
print doubleList

Output

[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]