16

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?

RKum
  • 758
  • 2
  • 12
  • 33
  • 5
    Possible duplicate of [Python: Difference between filter(function, sequence) and map(function, sequence)](https://stackoverflow.com/questions/18939596/python-difference-between-filterfunction-sequence-and-mapfunction-sequence) – Adam Jaamour Nov 30 '17 at 16:43
  • 1
    The understanding deepens by reading the docstrings attached. Type `filter?` or `map?` in a python console and read in a concise form what these are supposed to do. – Uvar Nov 30 '17 at 16:49

12 Answers12

26

They both work a little bit differently but you've got the right idea.

Map takes all objects in a list and allows you to apply a function to it Filter takes all objects in a list and runs that through a function to create a new list with all objects that return True in that function.

Here's an example

def square(num):
    return num * num

nums = [1, 2, 3, 4, 5]
mapped = map(square, nums)

print(*nums)
print(*mapped)

The output of this is

1 2 3 4 5
1 4 9 16 25

Here's an example of filter

def is_even(num):
    return num % 2 == 0


nums = [2, 4, 6, 7, 8]
filtered = filter(is_even, nums)

print(*nums)
print(*filtered)

The output of this would be

2 4 6 7 8
2 4 6 8
Zach B.
  • 663
  • 1
  • 7
  • 17
  • i have pas the square function in filter to see what i get, i get all the values of list (nums). it means filter function is basicaly used for "condition checking" and when i pas is_even function in map(), i get boolean value for each number in list (like, 1st item is 1, which is odd so , I get false, and so on,). so, i thought map() is basically used for operation on item of the list. am i right? – Synonian_raj Apr 11 '21 at 03:51
7

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.

barkat khan
  • 81
  • 1
  • 3
6

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.

Yashraj
  • 73
  • 1
  • 5
3

I think yes you got the picture pretty much. both Map and filter are ways of applying function to iterables. in Map you can use multiple iterables

definition : map(function_object, iterable1, iterable2,...)

whereas in filter only one iterable can be used

definition : filter(function_object, iterable)

further in filter the function_object has to return boolean only. for sake of example following is the Map with multiple iterables as input

list_a = [1, 2, 3]
list_b = [10, 20, 30]

map(lambda x, y: x + y, list_a, list_b) # Output: [11, 22, 33]
bharatk
  • 4,202
  • 5
  • 16
  • 30
Abhi
  • 61
  • 7
1

The filter() and map() functions are a little bit different. While Maps takes a normal function, Filter takes Boolean functions. As a matter of fact, filter are maps with conditional logic, a Boolean logic.

mahdi2080
  • 11
  • 2
0

Your example is too accurate. In filter function your supposed to pass a function and a list(the function must evaluate to true or false). If the element passed in the function returns true the filter function will put the element passed into a new list. Where as map function will take an element pass it through a function and return the output of the function and store that to the new list.

0

The main difference between a map and a filter is the return of values. A map will always have a representation for elements in the list. The filter will filter out the only elements that will meet the conditions in the function.

def checkElementIn(a):

    nameList = ['b','a','l','l']

    if a in nameList:
        return a 

testList = ['r','e','d','b','a','l','l']

m_list = map(checkElementIn,testList)

for i in m_list:
    print(i)

None
None
None
b
a
l
l

f_list = filter(checkElementIn,testList)

for i in f_list:
    print(i)

b
a
l
l

0

Those are completely different just take a look at this clear example down below:

def sqr(x):
    return x%2==0

mp = map(sqr, [-1,0,1,2,3,4,5,6])
print(list(mp))

[False, True, False, True, False, True, False, True]

fl = filter(sqr, [-1,0,1,2,3,4,5,6])
print(list(fl))

[0, 2, 4, 6]

as you can see in this clear example the filter doesn't care about the function results! It just checks which one of the list items would be true belonging to the calculation def, and the return is a list [0, 2, 4, 6] which means we have got a true result of numbers

Rai Rz
  • 493
  • 9
  • 22
0
#READ TIME 1 min. 
ages = [12,24,5,3,212,23,4,45,324,23]
age_filter = filter(lambda age : age >= 18, ages)
print(list(age_filter)) # filter gives result if there is condition

age_map = list(map(lambda age : age >= 18, ages))
print(age_map) # map will give boolean status but not actual values if 
condition

age_map_vals = list(map(lambda age : age * 18, ages))
print(age_map_vals) # here in map, condition is not given (means : 
multiplication will be performed with all elements)

# MAP AND FILTER WITH LIST OF WORDS
goats = ['EMINEM', '2upac', 'Dr.dre', 'snoop dog']
animals_filter = list(filter(lambda x : x != '2upac', goats))
print(animals_filter) # here condition > x != '2upac' is given

uppercase_map = list(map(lambda x : x.upper(), goats))
print(uppercase_map) # here condition is not given in map (means : 
x.upper() will applied to all elements)
0

One might illustrate the difference by implementing filter and map manually:

def map(func, iterable): # simplified version taking only one iterable for better comparison
    """
    Produces function results for all elements in iterable
    """
    for element im iterable:
        yield func(element) 

def filter(func, iterable):
    """
    Produces those elements in iterable for which function result is truthy
    """
    for element im iterable:
        if func(element):
            yield element

Note that you could implement filter using map:

from itertools import tee  # allow duplicating lazy iterator

def filter(func, iterable):
    # independent clones of iterable, beyond scope of question
    i1, i2 = tee(iterable)  

    return (e for e, r in zip(i1, map(func, i2)) if r)

This implementation makes little sense of course, but shows the

user2390182
  • 72,016
  • 6
  • 67
  • 89
-1

map(): Function will be applied to all objects of iterable, we can use as many literables as wee needed
filter(): Function will be applied to only those objects of iterable and added to result which item is True, we can use only one literable

In the below, code 0 is not add in the filter function because 0 is a representation for False in some cases so it is not added to the filter and added in the map function result

def check(num):
    return num*1


nums = [0,2, 4, 6, 7, 8]
result = filter(check, nums)

print(list(result))

def check(num):
    return num*1


nums = [0,2, 4, 6, 7, 8]
result = map(check, nums)

print(list(result))
-1

map() applies any applicable logic presented to any number of arguments of type list and returns an iterable containing values mapped to each respective members of the argument list(s).

example:

m = map(lambda x,y: 10+x+y, [1,2,3,4],[10,20,30,40])

print(list(m))

output: [21, 32, 43, 54]

filter() applies the condition specified to one argument of type list and returns an iterable containing values that satisfy the specified condition and thus selected from the argument.

example:

f = filter(lambda x: x<3, [1,2,3,4])

print(list(f))

output: [1, 2]

Yirgu
  • 1
  • 2