Lambda Functions
Lambda Functions
-------------------
* This lambda expressions is like "inline functions" of
C++.
* The lambda expressions are ultimately functions that
directly returns the result of expression.
* General syntax is:
expression_name = lambda para_list : expression
* If we print type of lambda expression, then it will
be "function".
For example:
-------------
add = lambda a,b:a+b
get_square = lambda n:n*n
print("Type of add is :", type(add))
print("Type of get_square is :", type(get_square))
For example:
--------------
add = lambda a,b:a+b
get_square = lambda n:n*n
a1 = add(10,20)
a2 = add(5.2, 6.5)
a3 = add(10, 2.5)
print(a1)
print(a2)
print(a3)
s1 = get_square(8)
s2 = get_square(2.65)
print(s1)
print(s2)
64
7.0225
==================================================
map():
* This function maps/directs/links the elements of
specified sequence (second parameter) to specified
function/lambda (first parameter)
* The result of map() is a sequence.
For example:
-------------
get_square = lambda n:n*n
ls = list(range(1,11))
ls2 = list(map(get_square, ls))
# maps elements of 'ls' with "get_square"
print(ls)
print(ls2)
For example:
-------------
add = lambda a,b: a+b
ls1 = range(1,11)
ls2 = range(10,101,10)
a1 = list(map(add, ls1, ls2))
print(a1)
==================================================
filter():
* This function filters the values/elements of
specified sequence for which result/condtion was TRUE.
* This function also requires two parameters:
- first is function name or lambda expression
- second is sequence.
* This function also returns a sequence.
For example:
-------------
get_evens = lambda n : n%2==0
ls = range(1,11)
a1 = list(filter(get_evens, ls))
print(a1)
===============================================
reduce():
* This function is present in module "functools".
* This function maps elements of specified sequence
with specified function.
* The result of this function will be single value.
For example:
-------------
from functools import reduce
add = lambda a,b : a+b
ls = range(1,11)
a1 = reduce(add, ls)
print(a1)
Example-2:
-----------
from functools import reduce
get_large = lambda a,b : a if a>b else b
ls = [21, 66, 84, 85, 30, 5, 61, 72]
a1 = reduce(get_large, ls)
print(a1)
=================================================
===================================================