0% found this document useful (0 votes)
5 views

Lambda to map reduce and filter

The document discusses Python functions, focusing on anonymous functions (lambda functions) and higher-order functions like map(), filter(), and reduce(). It explains the syntax, features, and use cases of lambda functions, as well as how to apply map(), filter(), and reduce to manipulate data in lists. Examples demonstrate the practical application of these concepts in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lambda to map reduce and filter

The document discusses Python functions, focusing on anonymous functions (lambda functions) and higher-order functions like map(), filter(), and reduce(). It explains the syntax, features, and use cases of lambda functions, as well as how to apply map(), filter(), and reduce to manipulate data in lists. Examples demonstrate the practical application of these concepts in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

2/3/22, 4:08 PM CS Lecture-1

return say_hi # It can be returned as an object

hi=greetings() #assisgning returned reference by outer function in some name


print(say_hi()) #It is still a local resources

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3964/2418066946.py in <module>
7
8 hi=greetings() #assisgning returned reference by outer function in some name
----> 9 print(say_hi()) #It is still a local resources

NameError: name 'say_hi' is not defined

ANONYMOUS FUNCTION OR LAMBDA


FUNCTION:
In Python, an "anonymous function" is a function that is defined without a name.

While normal functions are defined using the def keyword in Python, anonymous functions are
defined using the lambda keyword.

Hence, anonymous functions are also called lambda functions.

FEATURES OF LAMBDA FUNCTION:


1.Lambda functions all take a single argument.

2.In the definition of the lambdas, the arguments don’t have parentheses around them.

3.Multi-argument functions (functions that take more than one argument) are expressed in
Python lambdas by listing arguments and separating them with a comma (,) but without
surrounding them with parentheses:

USE OF LAMBDA FUNCTION:


We use lambda functions when we require a nameless function for a short period of time.

In Python, we generally use it as an argument to a higher-order function (a function that takes in


other functions as arguments). Lambda functions are used along with built-in functions like
filter(), map() etc. Lambda functions are frequently used with higher-order functions, which take
one or more functions as arguments or return one or more functions.

Python exposes higher-order functions as built-in functions or in the standard library. Examples
include map(), filter(), functools.reduce(), as well as key functions like sort(), sorted(), min(), and
max().

In [2]:
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 27/36
2/3/22, 4:08 PM CS Lecture-1

def add(x,y):
z=x+y
return z

print(add(5,3))

In [6]:
#Addition using anonymous/lambda function

#syntax "lambda" arguments: expression

s=lambda x,y:x+y #lambda function for addition


#lambda function definition returns a function at the time of compilation.
#returned function reference can be assigned in some variable name.
#this variable can be further used to call the defined lambda function.

In [7]:
#checking the type of defined lambda function

print(type(s)) #s has the reference of defined lambda function

<class 'function'>

In [8]:
#calling the lambda function through its referenced variable
#s has the reference of defined lambda function..
#so s can be called like a normal function by passing parameters mentioned in lambda
#expression written in lambda function will be evaluated and it return the value.

print(s(7,5))

12

In [9]:
#Square of a number using lambda

lambda x:(x*x)

#on compilation it has returned the created function

<function __main__.<lambda>(x)>
Out[9]:

In [10]:
#Square of a number using lambda

sq=lambda x:(x*x)
print(sq)

<function <lambda> at 0x000002551222C820>

In [11]:
#Square of a number using lambda

sq=lambda x:(x*x)
print(sq())

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 28/36


2/3/22, 4:08 PM CS Lecture-1

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9408/954540975.py in <module>
2
3 sq=lambda x:(x*x)
----> 4 print(sq())

TypeError: <lambda>() missing 1 required positional argument: 'x'

In [15]:
#Square of a number using lambda

sq=lambda x:(x*x)
print(sq(x=8)) #Parameter passed as keyword argument.
print(sq(5)) #Parameter passed as positional argument.

64
25

In [1]:
# A lambda function to calculate simple interest

si=lambda p,r,t: p*r*t/100


print(si(1000,5,5))
print(si(r=10,p=5000,t=5))

250.0
2500.0

In [3]:
#Lambda with default arguments:

sid=lambda p,r,t=5: p*r*t/100


print(sid(1000,5,10))
print(sid(5000,5))

500.0
1250.0

In [7]:
#Lambda function with user-defined function:

def multiplier(n): #user defined function


return lambda a:a*n

doubler=multiplier(2)
print(doubler(10))
print(doubler(5))
tripler=multiplier(3)
print(tripler(10))

20
10
30

In [8]:
x=10
y=15
z=x+y
if x>y:
print (z)

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 29/36


2/3/22, 4:08 PM CS Lecture-1

else:
print (x-y)

-5

In [ ]:
#Using "If-else" statement with lambda function.
#it's not advisable to use lambda for conditional statement.
#A conditional statement becomes very confusing when it's written like expression.

In [9]:
greater=lambda x,y: x if x>y else y

print("Greater number is:",greater(12,8))


print("Greater number is:",greater(12,20))

Greater number is: 12


Greater number is: 20

In [10]:
even_odd=lambda x:print("Even") if x%2==0 else print("Odd")

even_odd(12)
even_odd(7)
even_odd(9)

Even
Odd
Odd

In [11]:
#Lambda with non-keyword variable length arguments

var=lambda *v: print(v)

var()
var(1)
var(1,2,3,4,5)

()
(1,)
(1, 2, 3, 4, 5)

In [14]:
#Lambda with keyword variable length arguments

kvar=lambda **k: print(k)

kvar()
kvar(a=1,b=2,c=3,d=4,e=5)

{}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

What are map(), filter() and reduce()


functions in Python?

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 30/36


2/3/22, 4:08 PM CS Lecture-1

As mentioned earlier, map(), filter() and reduce() are inbuilt functions of Python. These functions
enable the functional programming aspect of Python. In functional programming, the arguments
passed are the only factors that decide upon the output. These functions can take any other
function as a parameter and can be supplied to other functions as parameters as well.

MAP() FUNCTION:
The map() function is a type of higher-order function. As mentioned earlier, this function takes
another function as a parameter along with a sequence of iterables and returns an output after
applying the function to each iterable present in the sequence.

Syntax: map(function,iterables)

Here, the function defines an expression that is in turn applied to the iterables. The map function
can take user-defined functions as well as lambda functions as a parameter.
User-defined functions can be sent to the map() method. The user or programmer is the only one who can
change the parameters of these functions. For example look at the code mention below:

In [4]:
def cs(a):
return a*a
x=map(cs,(1,2,3,4,5,6,7,8,9))

print(x)

print(tuple(x))

<map object at 0x0000024BDD8BC700>


(1, 4, 9, 16, 25, 36, 49, 64, 81)
In the above code you can see: x is a map object, as you can see. The map function is displayed next, which takes
“cs()” as a parameter and then applies “a * a” to all ‘iterables’. As a result, all iterables’ values are multiplied by
themselves before being returned.
In [6]:
#map with lambda

output=map(lambda x:x+3,[1,2,3,4,5])
print(output)
print(list(output))

<map object at 0x0000024BDD8BF670>


[4, 5, 6, 7, 8]

In [9]:
def doubler(x):
return x*2

li=[10,20,30,40,50]

new_list=map(doubler,li)
new_list=list(new_list)
print(new_list)

[20, 40, 60, 80, 100]

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 31/36


2/3/22, 4:08 PM CS Lecture-1

In [19]: keshav=[11,22,33,44,55]
do_li=list(map((lambda x:x*2),keshav))
print(do_li)

[22, 44, 66, 88, 110]

In [11]:
# map function with more than one iterables
#simple interest with map function

pli=[1000,2000,3000,4000,5000] #principal amount


rli=[5.5,5,7,1.5,8,4] #rate of intereset
tli=[2,3,4,4,6] #time

si_li=list(map((lambda p,r,t:p*r*t/100),pli,rli,tli))

print(si_li)

[110.0, 300.0, 840.0, 240.0, 2400.0]

In [14]:
#Map function can also use built-in or library function as arguments

num=['10','20','30','40','50']
#a map function to convert each element of the above list into integer
#so each elements will be typecasted in integer by using int function

num_li=list(map(int,num))
print(num_li)

[10, 20, 30, 40, 50]

In [24]:
#Program to calculate length of a string using map function
#built-in function "len()" will be used in map

st_li=("amartya","kush","aslam","shivangi","diksha","kavya")
st_len=tuple(map(len,st_li))

print(st_len)

(7, 4, 5, 8, 6, 5)

FILTER FUNCTION:
1. The filter() function is used to create an output list consisting of values for which the function
returns true.

2. The syntax of it is as follows: filter(function,iterables).

3. Function: function that test if elements of an iterable return true or false.

4. If None,then the function defaults to identity function which returns false if any elements are
false.

5. Iterables: Iterable which is to be filtered,could be set,list,tuples or containers of any iterators.

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 32/36


2/3/22, 4:08 PM CS Lecture-1

In [26]: #Filter function() with user-defined function:

def bekar_class(x):
if x>=5:
return x
y = filter(bekar_class, (1,2,3,4,5,6,7,8))
print(y)
print(list(y))

#As you can see, y is the filter object and the list
#is a list of values that are true for the condition (x>=5).

<filter object at 0x0000024BDD8BFFA0>


[5, 6, 7, 8]

In [27]:
y = filter(lambda x: (x>=5), (1,2,3,4,5,6,7,8))
print(list(y))

[5, 6, 7, 8]

In [2]:
#Filter function returns the elements of seq which produce True as a result
#for the condtion in function

seq=[True,False,True,True,False,False,None]
res=list(filter(lambda x:x,seq))
print(res)

[True, True, True]

In [4]:
#Filter out all the positive integers from a given list

cs=[-22,1,-34,45,67,-98,78,11,-65,65]

cs_obj=list(filter(lambda x:x>0,cs))
print("Positive Numbers are: ",cs_obj)

Positive Numbers are: [1, 45, 67, 78, 11, 65]

REDUCE() FUNCTION:
1. Python's reduce() implement a mathematical technique commonly known as "Folding" or
"Reduction". It is used to reduce a list of items to a single cumulative value.

2. The reduce() function in Python takes in a function and an iterable as an argument.

3. The function applied to the first two items in an iteable and generate a partial result.

4. The partial result,together with the third item in the iterable to generate another partial
result and the process is repeated untill the iterable is exhausted and then return a single
cumulative value.

5. Reduce() function is available in "functools module". So before using it we must import in our
scope. "from functools import reduce"

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 33/36


2/3/22, 4:08 PM CS Lecture-1

6. Syntax: reduce(function,iterable,[intializer]). Intializer[]: optional argument that provides a


seed value to the computation or reduction.

In [10]:
#Example reduce() function:

#Sum of all elements in a list


from functools import reduce

morning=[2,4,5,6,7,8,1,10]

cs=reduce(lambda x,y:x+y,morning)
print("Sum of elements in list is: ",cs)

Sum of elements in list is: 43

In [13]:
from functools import reduce

l=[10,20,30,40]

s=reduce(lambda x,y:x+y,l,1000) #third argument will be seed for the cumulative resul

print(s)

1100

In [14]:
#Sum of only even numbers using reduce in a given list

from functools import reduce

bolo=[1,2,3,4,5,6,7,8,9,10,11,12]

result=reduce(lambda x,y: x+y if y%2==0 else x,bolo,0)

print("Sum of even numbers in list: ",result)

Sum of even numbers in list: 42

In [15]:
#To find the max value in a list using reduce

li2=[22,33,4,5,77,99,1,43]

mx=reduce(lambda x,y: x if x>y else y,li2)

print(mx)

99

USING MAP(),FILTER() AND REDUCE()


TOGETHER:
When you use the map() function within filter() function, the iterables are first operated upon by
the map function and then the condition of filter() is applied to them.

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 34/36


2/3/22, 4:08 PM CS Lecture-1

Using filter() within map():


In [17]:
c= map(lambda x: x+x,filter(lambda x: (x>=3),(1,2,3,4,5,6,7,8)))
print(list(c))

[6, 8, 10, 12, 14, 16]

Using map() within filter():


In [18]:
c=filter(lambda x:(x>=3),map(lambda x:x+x,(1,2,3,4,5,6,7,8)))
print(list(c))

[4, 6, 8, 10, 12, 14, 16]

Using map() and filter() within reduce():


The output of the internal functions is reduced to the condition supplied to the reduce() function.

In [21]:
from functools import reduce

d=reduce(lambda x,y: x+y,map(lambda x:x+x,filter(lambda x:(x>=3),(1,2,3,4,5,6,7,8))))


print(d)

66

In [4]:
from functools import reduce
cs=[1,2,3,4,5,6,7,8]
sum_lk=reduce(lambda x,y: x+y,list(filter(lambda x:x%2==0,list(map(int,cs)))))
print (sum_lk)

20

In [6]:
#filter all the prime numbers within a given range and compute its summation.

from functools import reduce

def prime(n):
if n<=1:
return False
for i in range(2,n):
if n%i==0:
return False
else:
return True

#input range

x=int(input("Enter start point of the range: "))


y=int(input("Enter end point of the range: "))

cs=list(range(x,y+1)) #creation of list for a given range

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 35/36


2/3/22, 4:08 PM CS Lecture-1

#filterout all the prime numbers in a given range


prime_cs=list(filter(prime,cs))
print("All the prime within the given range is:",prime_cs)

#reduce all the prime numbers into sum

sum_cs=reduce(lambda x,y:x+y,prime_cs)
print("Sum of prime numbers is:",sum_cs)

Enter start point of the range: 10


Enter end point of the range: 50
All the prime within the given range is: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Sum of prime numbers is: 311

In [11]:
#Find all the cubes of each element in a list which are divisible by 3

jordar=[10,20,30,40,50,60,70,80,90,100]

#first map all the elements with its cube


cube_jordar=list(map(lambda x:x*x*x,jordar))
print("Cubes are: ",cube_jordar)

#filterout cubes which are divisible by 3

div_jordar=list(filter(lambda x: x%3==0,cube_jordar))

print("Divisible by 3: ",div_jordar)

#combined map within filter

div_jordar=list(filter(lambda x: x%3==0,list(map (lambda x: x*x*x,jordar))))


print(div_jordar)

Cubes are: [1000, 8000, 27000, 64000, 125000, 216000, 343000, 512000, 729000, 100000
0]
Divisible by 3: [27000, 216000, 729000]
[27000, 216000, 729000]

In [ ]:

localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 36/36

You might also like