Map and Filter function in Python


Welcome to the tutorial of Python



In this tutorial we will try to understand the powerful Map and Filter function


1) map() function - It returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.) 

Syntax : map( function, iteration ) ;
               where, 
                      function = It is a function to which map passes each element of given iterable.
                      iteration = It is a iterable which is to be mapped.


NOTE : You can pass one or more iterable to the map() function.


Conventional Method
Map Function Advantage

Def times2(var):
        Return var*2

Seq = [1,2,3,4,5]
Out = []

For num in seq:
       Out.append(times2(num))

Def times2(var):
        Return var*2

Seq = [1,2,3,4,5]
Out = list(map(times2,seq))














2) Filter functionThe filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. It uses lambda function.

Syntax : filter(lambda num: num%2==0, seq)

Eg: Print all words starting with s in the sequence 
        seq = ['sa','sb','df','rf','sz']

Ans : list(filter(lambda word: word[0] == 's', seq))

Map and Filter function in Python Map and Filter function in Python Reviewed by Analytics Pundit on November 30, 2019 Rating: 5

No comments:

Theme images by lishenjun. Powered by Blogger.