Question:
Consider variable x. do the following operation. Add 2 to x and square the result. Again add 3 to x and square the result. Do using anonymous functions in python
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
def func(n): return lambda x: (x+n)**2 #b is the lambda function where n = 2 and it accepts an arguement x b=func(2) print "b is a lambda function with n = 2 and type : ",type(b) #b is of the type 'function' what ever value is passed to it is #passed as x of the lambda function print "\npassing value 5 to function b and result is : ", print (b(5)) #here 5 is passed to x of lambda function c=func(3) print "\n\n\nc is a lambda function with n = 3 and type : ",type(c) print "\npassing value 5 to function c and result is : ", print (c(5)) b=5 print "\n\n\nb is now an integer with value : ",b c=4.5 print "\nc is now a float with value : ",c |
Explanation:
The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce().
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<span class="">b is a lambda function with n = 2 and type : <class 'function'> passing value 5 to function b and result is : 49 c is a lambda function with n = 3 and type : <class 'function'> passing value 5 to function c and result is : 64 b is now an integer with value : 5 c is now a float with value : 4.5</span> |
Leave a Reply