Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python difference between filter() and map()

Tags:

python

Being new to python I am just trying to figure out the difference between filter() and map(). I wrote a sample script as follows:

def f(x): return x % 2 == 0
def m(y): return y * 2

list = [1,2,3,4]

flist = filter(f, list)
print(list)
print(flist)

mlist = map(m, list)
print(list)
print(mlist)

We see that to both the filter and map we pass a list and assign their output to a new list.

Output of this script is

[1, 2, 3, 4]
[2, 4]
[1, 2, 3, 4]
[2, 4, 6, 8]

Question arises is that function call of both filter and map looks same so how will they behave if we interchange the contents of functions passed to them.

def f(x): return x * 2
def m(y): return y % 2 == 0

list = [1,2,3,4]

flist = filter(f, list)
print(list)
print(flist)

mlist = map(m, list)
print(list)
print(mlist)

This results in

[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[False, True, False, True]

This shows filter evaluates the function and if true it returns back the passed element. Here the function

def f(x): return x * 2

evaluates to

def f(x): return x * 2 != 0

In contrast map evaluates the function expression and returns back the result as items. So filter always expects its function to do comparison type of task to filter out the elements while map expects its functions to evaluate a statement to get some result.

Is this understanding correct?

like image 927
RKum Avatar asked Nov 30 '17 16:11

RKum


2 Answers

In map: Function will be applied to all objects of iterable. In filter: Function will be applied to only those objects of iterable who goes True on the condition specified in expression.

like image 61
barkat khan Avatar answered Sep 28 '22 11:09

barkat khan


As per my understanding below are the difference between map and filter:

def even(num):
    if(num % 2 == 0):
        return 'Even'

num_list = [1,2,3,4,5]

print(list(filter(even,num_list))) ->>>>>>>output: [2, 4]

print(list(map(even,num_list))) ->>>>>>> output: [None, 'Even', None, 'Even', None]

So, we can say that: filter(): formats new list that contains elements which satisfy specific condition. map(): function iterates through a all items in the given iterable and executes a function which we passed as an argument.

like image 38
Yashraj Avatar answered Sep 28 '22 10:09

Yashraj