Opening Hours :7AM to 9PM
In this article, you'll learn about the anonymous function, also known as lambda functions. You'll learn what they are, their syntax and how to use them (with examples).
lambda arguments: expressionLambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.
p = lambda x: x * 2 print(p(5)) Output 10In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is the expression that gets evaluated and returned.
p = lambda x: x * 2is nearly the same as:
def p(x): return x * 2
my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(filter(lambda x: (x%2 == 0) , my_list)) print(new_list) Output [4, 6, 8, 12]#same Program using Function
def myfun(): p = [1, 5, 4, 6, 8, 11, 3, 12] for x in p: if(x%2==0): print(x) myfun()
my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(map(lambda x: x * 2 , my_list)) print(new_list) Output [2, 10, 8, 12, 16, 22, 6, 24]# Same Program Using Function
def myfun(): p = [1, 5, 4, 6, 8, 11, 3, 12] for x in p: print(x*2,end="") myfun()