lambda python

Lambda Function in python. The Lambda function is same like a function that defined by def.the only difference is that it is anonymous and doesn’t require a name. Lamda functions generally used when you want to apply a quick function in a single line.

Before we will get started using this. Clearly you should know the python functions and what they do.

So, without worrying about creating a different function you can define lambda function in a single line of code. Lambda function has 3 major parts.

  1. The keyword “Lambda”
  2. Bound variables or parameters
  3. Lambda Function body

This function can only have 1 expression however the no.of parameters or variable can vary according to the function type. below is the simple syntax of lambda function in python

lambda parameter 1, parameter 2: expression

To understand it better let’s go through some interesting examples where we can use lambda function instantly.

my_list= [ lambda arg=y: y**10 for y in range(0,3)]

for values in my_list:
    print(values())

>> 10
   20
   30

Using if else statements: Read more: Map function in python

Max = lambda x, y : x if(x > y) else y

print(Max(10, 20))

>> 20

Lambda function example using filter and list:

my_list = [1,2,8,7,4,5,3,11, 21, 1]
filtered_result = filter (lambda x: x > 4, my_list) 
print(list(filtered_result))

>>[8,7,5,11,21]

Using map function:

my_list = [1,2,3,4]
filtered_result = map (lambda x: x*x, my_list) 
print(list(filtered_result))

>> [1,4,9,16]

With Reduce Function:

from functools import reduce
my_list = [1,2,3,4,5,6]
product = reduce (lambda a, b: a*b, my_list)
print(product)

>> 720

Explanation: Here we applied Lambda function and after that we will be using reduce from functools library. this function just multiplies are value and the result is again multiply with next value until you reach the limit of your list, tuple.

Undoubtedly you can use this function in particularly anywhere. however don’t write large functions in lambda because it will get complicated and very hard to understand to the learners. Besides it is easy to use and implement.

If you want to see more examples of Lambda functions You can learn from Geeksforgeeks, programiz, javatpoint. Thanks for reading in educatedinfo.

LEAVE A REPLY

Please enter your comment!
Please enter your name here