Lambdas are a short way of writing simple functions. There are certain scenarios where we only want to use the function once and may not need it again. If the function is simple then lambdas are a convenient way to express that.
File: "lam2.py"
def inc(x):
return x + 10
print( inc(5) )
lam1 = lambda x : x + 10
print( lam1(2) )
print( (lambda x : x + 10 )(3) )
The syntax is :
lambda "arguments" : return expression
Exercise:
Write a lambda expression that takes 2 arguments and returns their product. Test it out with some sample
arguments.
A function returning a lambda function.
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print( mydoubler(11) )
The first call "myfunc" creates a function for us to use . The function returned is " a * 2 " .
Similarly we can create other functions.
File: "lam1.py"
counters = [1, 2, 3, 4]
def inc(x):
return x + 10
print( list(map(inc, counters)) )
print( list(map((lambda x: x + 3), counters)) )
The "map" function returns a list of results after applying the first argument ( a function ) to each item in the list.
[amittal@hills Lambda]$ python3 lam1.py
[11, 12, 13, 14]
[4, 5, 6, 7]