Lambda or Anonymous Function in Python

In this class, we discuss Lambda or Anonymous Function in Python.

For Complete YouTube Video: Click Here

Lambda or Anonymous Function

The reader should have prior knowledge of functions. Click here.

Defining Lambda Functions:

We define lambda function like z=lambda x: x*2

In the lambda function definition, x is the function parameter.

In the lambda functions, we will have only one expression.

z= lambda x: x*2
print(z(5))

In our example, x*2 is the expression.

Lambda functions can have any number of parameters.

The lambda function definition will create a function object, and the reference is returned.

In the example above, variable z will take the lambda function reference.

The variable z can be used as a function.

Example: z(5) will take one argument value 5. function return value 10.

We do not have any name for the function. That is the reason we call anonymous function.

Similarly, we write the above program using functions.

The program is given below.

def f(x):
    return x*2
print(f(5))

Lambda Functions with Two Parameters

Example:

z=lambda x,y:x+y
print(z(2,5))

Use of Lambda Function

In our previous class, we discussed map and filter functions.

In the map and filter function examples, we have a situation to use single expression functions.

In the situations where we need single expression functions. We can use lambda functions.

The examples are given below.

ages = [5, 12, 17, 18, 24, 32]

def myFunc(x):
  if x < 18:
    return False
  else:
    return True
adults = filter(myFunc, ages)
for x in adults:
  print(x)

In the above example, we have defined a function and using that function in the filter function.

We can define the lambda function in the filter function instead of functions.

By using the lambda function, we can reduce the code.

The example is given below.

ages = [5, 12, 17, 18, 24, 32]

adults = filter(lambda x: x>=18, ages)

for x in adults:
  print(x)