Python reduce

Python reduce() Function

Python reduce() Function is a function that implements a mathematical technique called folding or reduction. reduce() is useful when you need to apply a function to an iterable and reduce it to a single cumulative value. Python’s reduce() is popular among developers with a functional programming background, but Python has more to offer.

The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is defined in “functools” module.

reduce() function reduces sequence of elements into a single element by applying the specified function.

reduce(function,sequence):

reduce() function present in functools module and hence we should write import statement.

Example 1:

from functools import *

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

result=reduce(lambda x,y:x+y,l)

print(result) # 150

 

Example 2:

result=reduce(lambda x,y:x*y,l)

print(result) #12000000

 

Example 3:

from functools import *

result=reduce(lambda x,y:x+y,range(1,101))

print(result) #5050

 

Related Posts:

Python Tutorial – Learn Python

What is Python? What makes Python so Powerful?

Variables in Python – Constant, Global & Static Variables

Namespacing and Scopes in Python

Operators in Python

Data Types in Python

STRING Data Type in Python

LIST Data Structure in PYTHON

TUPLE Data Structure in PYTHON

Differences between List and Tuple

SET Data Structure in PYTHON

DICTIONARY Data Structure in PYTHON

Database Programming in Python

What is Multithreading in Python?

Python Exception Handling Using try, except and finally statement

File Handling in Python

Python Random module

Python map() Function

Python filter() Function

Lambda Function in PYTHON (Anonymous Function)

Python Interview Question And Answers