Important Notice:

Course Content
The Calendar Module
Library Function/Predefined Functions
0/4
Sys Module
Library Function/Predefined Functions
0/2
OS Module
Library Function/Predefined Functions
0/2
Functions in Python (Chapter-10) M3-R5
About Lesson

reduce() Function 

          This function is used to reduce a sequence of elements to a single value by processing the elements according to a function supplied. It returns a single value. This function is a part of functools module so you have to import it before using

Syntax:- from functools import reduce

Reduce(function name, sequence)

With lambda function

from functools import reduce

a=[5,10,15,18]

res=reduce(lambda n,m:n+m,a)

print(res)

output

48

Without lambda function

from functools import reduce

def myfun(a,b):

    return a+b

val=[10,20,30]

add=reduce(myfun,val)

print(“Addition is “,add)

output

Addition is  60

 

 

1: Finding max number In the list using reduce () function.

Without lambda function

from functools import reduce

def myfun(a,b):

    if a>b:

        return a

    else:

        return b

val=[20,10,30,50]

max=reduce(myfun,val)

print(“maximum no. is “, max)

output

maximum no. is  50

With lambda function

from functools import reduce

val=[20,10,30,60,50]

max=reduce(lambda a,b:a if a>b else b,val)

print(“max is “,max)

output

max is  60

error: Content is protected !!