Python: Difference between filter(function, sequence) and map(function, sequence)

Question:

I’m reading through the Python documentation to really get in depth with the Python language and came across the filter and map functions. I have used filter before, but never map, although I have seen both in various Python questions here on SO.

After reading about them in the Python tutorial, I’m confused on the difference between the two. For example, from 5.1.3. Functional Programming Tools:

>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]

and

>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

These looked almost exactly the same in function to me, so I went into terminal to run Python interactively and tested out my own case. I used map for both the first and second instances above, and for the first one ( return x % 2 != 0 and x % 3 != 0 ) it returned a list of booleans rather than numbers.

Why does map sometimes return a boolean and other times the actual return value?

Can someone explain to me exactly the difference between map and filter?

Asked By: samrap

||

Answers:

list(map(cube, range(1, 11)))

is equivalent to

[cube(1), cube(2), ..., cube(10)]

While the list returned by

list(filter(f, range(2, 25)))

is equivalent to result after running

result = []
for i in range(2, 25):
    if f(i):
        result.append(i)

Notice that when using map, the items in the result are values returned by the function cube.

In contrast, the values returned by f in filter(f, ...) are not the items in result. f(i) is only used to determine if the value i should be kept in result.


In Python2, map and filter return lists. In Python3, map and filter return iterators. Above, list(map(...)) and list(filter(...)) is used to ensure the result is a list.

Answered By: unutbu

filter(), as its name suggests, filters the original iterable and retents the items that returns True for the function provided to filter().

map() on the other hand, apply the supplied function to each element of the iterable and return a list of results for each element.

Follows the example that you gave, let’s compare them:

>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> range(11)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> map(f, range(11))  # the ones that returns TRUE are 1, 5 and 7
[False, True, False, False, False, True, False, True, False, False, False]
>>> filter(f, range(11))  # So, filter returns 1, 5 and 7
[1, 5, 7]
Answered By: CT Zhu

map and filter function in python is pretty different because they perform very differently. Let’s have a quick example to differentiate them.

map function

Let’s define a function which will take a string argument and check whether it presents in vowel letter sequences.

def lit(word):
    return word in 'aeiou'

Now let’s create a map function for this and pass some random string.

for item in map(lit,['a','b','e']):
    print(item)

And yes it’s equivalent to following

lit('a') , lit('b') , lit('e')

simply it will print

True
False
True 

filter function

Now let’s create a filter function for this and pass some random string.

for item in filter(lit,['a','b','e']):
    print(item)

filter as the name implies, filters the original iterable and retents the items that return True for the function provided to the filter function.

Simply it will print

a
e

Fork it here for future reference, if you find this useful.

Answered By: M.Innat

filter(function, iterable) function (pointer, like in C) return boolean type

map(function, iterable) function (pointer, like in C) return e.g. int

def filterFunc(x):
    if x & 1 == 0:
        return False
    return True


def squareFunc(x):
    return x ** 2


def main():
    nums = [5, 2, 9, 4, 34, 23, 66]
    odds = list(filter(filterFunc, nums))   # filter(function, iterable)
    print(odds)

    square = list(map(squareFunc, nums))    # map(function, iterable)
    print(square)


if __name__ == '__main__':
    main()
Answered By: andrew

Filter–Returns the true value’s position


var_list = [10,20,0,1]

var_b = list(filter(lambda var_a : var_a*2,var_list))

print("Values are",var_b)

Output


Values are [10, 20, 1]

Map–Returns the actual result


var_list = [10,20,0,1]

var_b = list(map(lambda var_a : var_a*2,var_list))

print("Values are",var_b)

Output


Values are [20, 40, 0, 2]

Reduce–Take the first 2 items in the list,then calls function,
In next function call,the result of previous call will be 1st argument and 3rd item in list will be 2nd argument


from functools import *

var_list = [10,20,0,1]

var_b = list(map(lambda var_a : var_a*2,var_list))

print("Values of var_b ",var_b)

var_c = reduce(lambda a,b:a*2,var_b)

print("Values of var_c",var_c)

Output


Values of var_b [20, 40, 0, 2]

Values of var_c 160

Answered By: Sivakumarj