Lambda Function in python

In Python, the lambda function is a special kind of nameless inline function that consists of a unique expression that is evaluated when called, like the def function. 

Syntax of the lambda function

The syntax to create a lambda function is represented as follows:

lambda parameter(s) : expression

Parameter(s): This is the value passed to the lambda function.

expression: This is what is to be executed or returned.

The lambda function can have any number of arguments, but the returned or executed expression must be only one.  

Lambda function examples

greeting = lambda name: print(f'Hello, {name}!')
greeting("James")

Output: Hello, James!

The function is assigned to the variable greeting. The argument of the function is name. The expression to be executed is print(f 'Hello, {name}!'). Finally, we have to call the function with its parameter for it to be executed.

The lambda function can also take any number of arguments.

sums = lambda x, y : print(x + y)
sums(58, 70)

Output: 128

The lambda function is assigned to a variable called sums. The arguments of the function are two in number (x and y). The function expects these two parameters in order for the expression to be executed.

Why use the lambda function?

The lambda function is best used in a function because of its anonymous nature.

Using lambda function in other function.

def func(a):
     return lambda b: a*b
result1 = func(2) 
print(result1(7))

Output: 14

Let's use the lambda function with other built-in functions in python.

Using lambda with map() function.

A function and a list are passed as an argument in a map() function. 

list1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
result = list(map(lambda a: a**2, list1))
print(result)

Output: [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

We found the square of each number in the list1 using the map() and lambda function. The output is rendered as the square of each number in the list.

Using lambda with the filter() function.

The filter() function accommodates two parameters. They include a function or method and an iterator like a list. 

list1 = [2, 9, 7, 8, 10, 12, 13, 16, 15, 20]
result = list(filter(lambda a: a%2 == 0, list1))
print(result)

Output: [2, 8, 10, 12, 16, 20]

To print the even numbers in the list1, the filter() and lambda functions are combined.  The filter() function is used to filter the expression made by the lambda function. The filter() function will return the values of the list that is True for the expression  a%2 == 0.

Using lambda function with list comprehension

Finally, we will use the lambda function combined with a list comprehension to print out the multiples of 5 in a particular range of numbers.

multiple_of_5 = [lambda a = a: a*5 for a in range(1, 10)]
for i in multiple_of_5:
     print(i(), end=" ")

Output: 5 10 15 20 25 30 35 40 45