Skip to main content

Python Map, Filter, and Reduce

Map Function:

Python map function is used to return the new list from another list ,this accepts another function and a sequence of ‘iterables’  as parameter  and returns the resulting sequence after applying the function to each iterable .

Syntax:

map(func, iterables)

Example:

list_1=(1, 2, 3, 4)
res=map(lambda x: x**2, numbers)
print(list(res))

Output: [1, 4, 9, 16]

Filter Function: 

In Python, filter function is a built-in function which is used to returns  an iterator were the each element in a sequence is filtered through a function to test if it satisfy a given condition or not.

Syntax:

filter(function, iterable)

Example:

def func_1(var):
    vowels = ['a', 'e', 'i', 'o', 'u']
    if (var in vowels):
        return True
    else:
        return False
  
  
# sequence
list_1 = ['p', 'y', 't', 'h', 'o', 'n', 'p', 'r','o','g','r','a','m']
  
# using filter function
filtered = filter(func_1, list_1)
  
print('The filtered letters are:')
for x in filtered:
    print(x)

Output:

The filtered letters are:
o
o
a

Reduce Function :

In Python, reduce() function is defined in the functools module. It is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along.

Syntax:

reduce(func, iterable ,[initial])

Example:

from functools import reduce
def func_1(a,b):
    return a*b

res=reduce(func_1, range(1,10))
print ('Factorial of 9: ', res)

Output: Factorial of 9: 362880

Tags
Submitted by devanshi.srivastava on August 18, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.